广度优先遍历BFS
先遍历这个节点的相邻节点,再依次遍历每个相邻节点的相邻节点。
树的广度优先遍历,每个节点的值即为它们的遍历顺序。所以广度优先遍历也叫层序遍历.
广度优先则采用的是队列的形式, 即先进先出
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
var levelOrder = function(root) {
if (!root) return [];
let result = [];
let queue = [root];
while(queue.length !== 0) {
let len = queue.length;
let arr = [];
for(let i = 0; i < len; i++) {
let node = queue.shift();
arr.push(node.val);
node.children && queue.push(...node.children);
}
result.push(arr);
}
return result;
};
// arr正在遍历的序列, children放入未排列的序列中
function bfs(arr) {
let result = [];
for(let i = 0; i < arr.length; i++) {
result.push(arr[i].title);
if (arr[i].children) {
arr.push(...arr[i].children);
}
}
console.log(result);
}
深度优先遍历DFS
主要思路是从图中一个未访问的顶点 V 开始,沿着一条路一直走到底,然后从这条路尽头的节点回退到上一个节点,再从另一条路开始走到底…,不断递归重复此过程,直到所有的顶点都遍历完成,它的特点是不撞南墙不回头,先走完一条路,再换一条路继续走。
深度优先采用的是堆栈的形式, 即先进后出
function dfs(root) {
let result = [];
if (root) {
let stack = [root];
while(stack.length) {
let node = stack.shift();
result.push(node.val);
let children = node.children;
for(let i = children.length - 1; i > -1; i--) {
stack.unshift(children[i])
}
}
}
return result;
}
// 递归
function dfs(arr) {
let result = [];
fn(arr);
console.log(result);
return result;
function fn(arr) {
for(let i = 0; i < arr.length; i++) {
result.push(arr[i].title);
if (arr[i].children) {
fn(arr[i].children);
}
}
}
}