Open weijiyang opened 4 years ago
伪代码 主要是通过两个数组进行流转 每当遍历一个父节点 子节点保存到另一个数组中 当遍历完父节点的时候将两个数组替换 子节点数组变为父节点数组 以此类推...
let widthTraversal2 = (node) => {
let nodes = []
let stack = []
if (node) {
stack.push(node)
while (stack.length) {
let item = stack.shift()
let children = item.children
nodes.push(item)
// 队列,先进先出
// nodes = [] stack = [parent]
// nodes = [parent] stack = [child1,child2,child3]
// nodes = [parent, child1] stack = [child2,child3,child1-1,child1-2]
// nodes = [parent,child1,child2]
for (let i = 0; i < children.length; i++) {
stack.push(children[i])
}
}
}
return nodes
}
深度优先遍历 DFS