树的深度优先和广度优先遍历

227 字
1 分钟
树的深度优先和广度优先遍历

以看书为例子 深度优先遍历就是看第一章节然后和第一章节内容,然后看完第一章节再看第二章节以及内容。 广度优先遍历就是先看标题>>所有目录>>所有小节>>内容。

深度优先遍历(DFS)#

  1. 访问根节点。
  2. 对根节点的children挨个进行深度优先遍历。

image-20250512161044962
image-20250512161044962

递归

const dfs = (root) => {
if(root === null) return
root.children.forEach(leaf => {
console.log(leaf.val)
dfs(leaf)
})
}

栈

const dfs = (root) => {
if(root === null) return
const stack = [root]
while(stack.length > 0) {
const node = stack.pop();
console.log(node.val)
node.children.forEach(leaf => {
stack.push(leaf)
})
}
}

广度优先遍历(BFS)#

  1. 新建一个队列,把根节点入队。

  2. 遍历队列

    • 把队头出队并访问。

    • 把队头的children 挨个入队。

重复2,直到队列为空。

image-20250512163432700
image-20250512163432700

const bfs = (root) => {
if (!root) return;
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
console.log(node.val);
node.children.forEach(leaf => {
queue.push(leaf);
});
}
}
}

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

树的深度优先和广度优先遍历
https://an2333.com/posts/basic/algorithm/tree/深度优先和广度优先遍历/
作者
Annan
发布于
2025-05-21
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
Annan
写点前端,聊点 AI。
公告
博客已迁移到 Astro + Firefly,旧文章正在陆续搬家中。
分类
标签
站点统计
文章
50
分类
7
标签
28
总字数
84,160
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
GitHub Actions
博客版本
Firefly v6.16.8
文章许可
CC BY-NC-SA 4.0
文章目录