const tree = {
name: 1,
child: [
{
name: 2,
child: [{
name: 3,
child: null,
}]
},
{
name: 4,
child: [{
name: 5,
child: null,
}]
}
]
};
// 深度优先遍历
function deepFirstSearch(tree) {
let res = [];
if (!tree) {
return res;
}
let stack = [tree];
while(stack.length) {
// 这个地方把数组最后一项放出来
const node = stack.pop();
res.push(node.name);
const child = node.child;
if (child) {
// 这个地方要从child的最后一项遍历开始,因为使用了数组模拟栈的形式,先进后出
for(let i = child.length - 1; i >= 0; --i) {
stack.push(child[i]);
}
}
}
return res;
}
console.log(deepFirstSearch(tree)); // 结果[1, 2, 3, 4, 5]
// 广度优先遍历
function breadthfirstSearch(tree) {
let res = [];
if (!tree) {
return res;
}
let stack = [tree];
while(stack.length) {
// 这个地方把数组第一项放出来
const node = stack.shift();
res.push(node.name);
const child = node.child;
if (child) {
// 按照顺序把child推送栈中,使用队列的形式模拟
for(let i = 0; i < child.length; ++i) {
stack.push(child[i]);
}
}
}
return res;
}
console.log(breadthfirstSearch(tree)); // 结果[1, 2, 4, 3, 5]
console