深度优先遍历
let dfc = (node) => {
let stack = [] // 栈
let nodes = [] // 存所有节点
if (node) {
stack.push(node) // 假如有节点就存到栈中
while (stack.length) {
let item = stack.pop() // 出栈
nodes.push(item)
let children = item.children // 拿到子节点
// 每层从右往左取 取到放进stack
for (let i = children.length - 1; i >= 0; i--) {
stack.push(children[i])
}
}
}
return nodes // 所有节点返回
}
广度优先遍历
let bfs = (node)=>{
let stack = [] // 队列
let nodes = [] // 返回的节点
if(node){
stack.push(node)
while(stack.length){
let item = stack.shift() // 从前面去
nodes.push(item)
let children = item.children
for(let i=0;i<children.length;i++){
stack.push(children[i])
}
}
}
return nodes
}