1.深度优先查找(DFS)
这个是要进行遍历的树形节点
//
const root = [
{
"id":1,
"pid":null,
"key":1,
"title":"1-1111",
"children":[
{
"id":2,
"pid":1,
"key":2,
"title":"2-1111",
"children":[
{
"id":4,
"pid":2,
"key":4,
"title":"8-1111",
"children":[]
},
{
"id":5,
"pid":2,
"key":5,
"title":"9-1111",
"children":[
{
"id":7,
"pid":5,
"key":7,
"title":"5-1111",
"children":[]
},
{
"id":8,
"pid":5,
"key":8,
"title":"8-1111",
"children":[]
},
]
},
{
"id":6,
"pid":2,
"key":6,
"title":"10-1111",
"children":[]
},
]
},
{
"id":3,
"pid":1,
"key":3,
"title":"9-1111",
"children":[]
}
]
}
]
方法1.递归回溯
function depthFirstSearchRecursion (target) {
const res = []; // 存放结果
const dfs=(data)=> {
data.forEach(node=> {
res.push(node.id); // 将当前节点 id 存放进结果
// 如果当前节点有子节点,则递归调用
if (node.children && node.children.length > 0) {
dfs(node.children);
}
})
}
dfs(target);
return res;
}
方法2.栈结构
function depthFirstSearchNoRecursion (target) {
const res = [];
const stack = target.slice();
// console.log(stack)
while (stack.length > 0) {
const node = stack.shift(); // 最上层节点出栈
res.push(node.id);
// 如果该节点有子节点,将子节点存入栈中,继续下一次循环
const len = node.children && node.children.length;
for (let i = len - 1; i >= 0; i--) {
stack.unshift(node.children[i]);
}
}
return res;
}
2. 广度优先查找(BFS)
采用队列,先进先出
function breadthFirstSearch(target) {
const res = [];
const queue = target.slice();
while (queue.length > 0) {
const node = queue.shift(); // 最上层节点出栈
res.push(node.id);
// 如果该节点有子节点,将子节点存入队列中,继续下一次循环
const len = node.children && node.children.length;
for (let i = 0; i < len; i++) {
queue.push(node.children[i])
}
}
return res;
}