构造一个树模型
const tree = {
val: 'a',
children: [
{
val: 'b',
children: [{
val: 'd',
children: [{
val: 'g',
children: []
}, {
val: 'h',
children: []
}]
}]
}, {
val: 'c',
children: [{
val: 'e',
children: [{
val: 'i',
children: []
}, {
val: 'j',
children: []
}]
}, {
val: 'f',
children: [{
val: 'k',
children: []
}]
}]
}]
}
广度优先算法
广度优先算法是先遍历第一级的平行节点,再遍历第二级的平行节点,依次类推,需要用到队列来缓存平行节点的子级。主要步骤为:
- 新建一个队列,把根节点入队
- 把附头出队并访问
- 把队头的
children
依次入队 - 重复第二、三步,直到队列为空
// 广度优先算法
const bfs = (root) => {
let queue = [root]
while (queue.length) {
const head = queue.shift();
console.log(head.val)
head.children?.forEach(child => {
queue.push(child)
})
}
}
bfs(tree)
输出
a
b
c
d
e
f
g
h
i
j
k
深度优先算法
深度优先算法主要利用递归处理,先遍历上一个节点的所有深度,再遍历平行节点的所有深度
//深度优先算法
const dfs = (root) => {
console.log(root.val)
root.children?.forEach(item =>{
dfs(item)
})
}
dfs(tree)
输出
a
b
d
g
h
c
e
i
j
f
k