1.深度优先遍历:
深度优先遍历:尽可能深的搜索树的分支。
例如:
算法口诀:
1.访问根节点。
2.对根节点的children挨个进行深度优先遍历。
实例:
const tree = {
val: 'a',
children: [{
val: 'b',
children: [
{
val: 'd',
children: []
},
{
val: 'e',
children: []
}
]
},
{
val: 'c',
children: [
{
val: 'f',
children: []
},
{
val: 'g',
children: []
}
]
}]
}
const dfs = (root) => {
console.log(root.val);
root.children.forEach(dfs);
}
dfs(tree)
2.广度优先遍历:
广度优先遍历:先访问离根节点最近的节点。
例如:
算法口诀:
1.新建一个队列,把根节点入队。
2.把队头出队并访问。
3.把队头的children挨个入队。
4.重复第二、三步,直到队列为空。
实例:
const tree = {
val: 'a',
children: [{
val: 'b',
children: [
{
val: 'd',
children: []
},
{
val: 'e',
children: []
}
]
},
{
val: 'c',
children: [
{
val: 'f',
children: []
},
{
val: 'g',
children: []
}
]
}]
}
const bfs = (root) => {
const q = [root];
while (q.length > 0) {
const n = q.shift();
console.log(n.val);
n.children.forEach(child => {
q.push(child);
});
}
}
bfs(tree)