代码实现
BFS (广度优先搜索)
function BFS(node) {
let nodeList = [];
if (node) {
let temp = [];
temp.unshift(node);
while (temp.length) {
let item = temp.shift();
nodeList.push(item);
let children = item.chidren;
for (let i = 0; i < children.length; i++) {
temp.push(children[i])
}
}
}
return nodeList
}
DFS (深度优先搜索)
let nodeList = [];
function DFS(node,nodeList) {
if (node) {
nodeList.push(node);
let children = node.children;
for (let i = 0; i < children.length; i++) {
DFS(children[i],nodeList)
}
}
return nodeList
}