// 深度优先搜索 递归
let DFS = (node, nodeList = []) => {
//node不能为null
if (node !== null) {
nodeList.push(node)
let children = node.children || []
//如果children.length存在
for (let i = 0; i < children.length; i++) {
//递归调用
DFS(children[i], nodeList)
}
}
return nodeList
}
// 实现一个深度优先搜索算法(非递归)
function dfs(tree, name) {
// 请在这里实现
const res = [];
if (tree) {
const stack = [];
// 利用栈特性先进后出
stack.push(tree);
while (stack.length !== 0) {
const item = stack.pop();
res.push(item);
if (item.children) {
for (let i = item.children.length - 1; i >= 0; i--) {
stack.push(item.children[i]);
}
}
}
}
console.log("dfs", res);
return res;
}
// 广度优先搜索
// 使用队列的思想
function BFS(root) {
if (!root) return;
const list = [];
const queue = [root];
while (queue.length) {
const item = queue.shift();
list.push(item);
if (item.children) {
item.children.forEach((child) => {
queue.push(child);
});
}
}
return list;
}
深度优先搜索DFS和广度优先搜索BFS
于 2022-05-25 11:44:57 首次发布