多叉树的深度优先和广度优先遍历
- 深度优先的思想比较常见,就是使用递归,没什么好说的。
- 广度优先的思想,主要是需要借助一个队列,不停地将同一层级的子节点放入队列,然后依次从队列中取出执行。
/**
* var Node = {
* data: null,
* children: Array<Node>
* }
*/
function breadthFirstTraversal(node) {
let nodeList = [node];
while(nodeList.length > 0) {
const current = nodeList.shift();
console.log(current.data);
if(current.children && current.children.length > 0) {
nodeList.push(...current.children);
}
}
}
function depthFirstTraversal(node) {
function traversal(node) {
console.log(node.data);
if(node.children && node.children.length > 0) {
for(let i = 0;i < node.children.length;i++) {
traversal(node.children[i]);
}
}
}
traversal(node);
}
const node = {
data: 1,
children: [
{
data: 2,
children: [
{
data: 3
}
]
},
{
data: 4,
children: [
{
data: 5,
children: [
{
data: 6
}
]
}
]
},
{
data: 7
}
]
}
breadthFirstTraversal(node); // 1 2 4 7 3 5 6
depthFirstTraversal(node); // 1 2 3 4 5 6 7