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) {
for(let i = child.length - 1; i >= 0; --i) {
stack.push(child[i]);
}
}
}
return res;
}
console.log(deepFirstSearch(tree));
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) {
for(let i = 0; i < child.length; ++i) {
stack.push(child[i]);
}
}
}
return res;
}
console.log(breadthfirstSearch(tree));
console