JingchaoZhao / js-learning

knowledge of webs
0 stars 0 forks source link

tips: 深度遍历 广度遍历 #13

Open JingchaoZhao opened 5 years ago

JingchaoZhao commented 5 years ago

深度遍历

JingchaoZhao commented 5 years ago

let deepTra = (node, nodeList = []) => { if (node !=== null) { nodeList.push(node) let children = node.children for (let i = 0; i < children.length; i++) { deepTra(children[I], nodeList) } } return nodeList }

JingchaoZhao commented 5 years ago

let deepTraversal3 = (node) => { let stack = [] let nodes = [] if (node) { // 推入当前处理的node stack.push(node) while (stack.length) { let item = stack.pop() let children = item.children nodes.push(item) // node = [] stack = [parent] // node = [parent] stack = [child3,child2,child1] // node = [parent, child1] stack = [child3,child2,child1-2,child1-1] // node = [parent, child1-1] stack = [child3,child2,child1-2] for (let i = children.length - 1; i >= 0; i--) { stack.push(children[i]) } } } return nodes }

JingchaoZhao commented 5 years ago

广度优先

image