广度优先遍历深度优先遍历

深度优先遍历:

Depth-First.png
1
2
3
4
5
6
7
function DFS(node) {
if(!node) {return}
console.log(node.nodeName);
Array.from(node.children).forEach(child => {DFS(child)});
}

广度优先遍历:

Breadth-First.png
1
2
3
4
5
6
7
8
9
10
11
function BFS(node) {
var queue = [node];
while(queue.length) {
var current = queue.shift();
console.log(current.nodeName);
Array.from(current.children).forEach(child => queue.push(child));
}
}