先简单看下树的结构
const tree = {
name: 'A',
children: [
{
name: 'B',
children: [
{name: 'D'},
{name: 'E'},
]
},
{
name: 'C',
children: [
{name: 'F'},
{name: 'G'}
]
}
]
}
一、深度优先遍历
先遍历根节点,然后在遍历左子树,直到左子树全部遍历完,再去遍历右子树。
let nodes= [];
function dfs(root) {
nodes.push(root.name);
if (root.children) {
root.children.forEach(dfs);
}
return nodes;
}
const result = dfs(tree);
console.log(result);
二、广度优先遍历
先遍历根节点,然后在遍历第一层的子节点,完事后在遍历第二层子节点,依此类推,逐层遍历
let nodes = [];
function bfs(root) {
const quenee = [root];
while (quenee.length > 0) {
const node = quenee.shift();
nodes.push(node.name);
if (node.children) {
node.children.forEach(child => {
quenee.push(child);
})
}
}
return nodes;
}
const result = bfs(tree);
console.log(result);