Data
let node = {
txt: '1',
children: [{
txt: '11',
children: [{
txt: '111'
}, {
txt: '112'
}, {
txt: '113'
}]
}, {
txt: '12',
children: [{
txt: '121'
}, {
txt: '122'
}, {
txt: '123'
}]
}, {
txt: '13',
children: [{
txt: '131'
}, {
txt: '132'
}, {
txt: '133'
}]
}]
}
DFS
let stack = [node]
while (stack.length > 0) {
let node = stack.shift()
console.log(node.txt)
if (node.children) {
let children = node.children
for (let i = children.length-1; i >= 0; i--) {
stack.unshift(children[i])
}
}
}
BFS
let queue = [node]
while(queue.length > 0) {
let obj = queue.shift()
console.log(obj.txt)
if (obj.children) obj.children.forEach(item => queue.push(item))
}
网友评论