二叉树的先中后序遍历

169 字
1 分钟
二叉树的先中后序遍历

先序遍历 根左右#

递归

var preorderTraversal = function(root) {
const res = []
const dfs = (root) => {
if(root === null) return
res.push(root.val)
dfs(root.left)
dfs(root.right)
}
dfs(root)
return res
};

栈

var preorderTraversal = function(root) {
if (!root) return;
const res = []
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
res.push(node.val)
// 注意:因为栈是LIFO,所以先压入右子节点,再压入左子节点
if (node.right) stack.push(node.right);
if (node.left) stack.push(node.left);
}
return res
};

中序遍历 左根右#

递归

var inorderTraversal = function(root) {
const res = []
const dfs = (root) => {
if(root === null) return
dfs(root.left)
res.push(root.val)
dfs(root.right)
}
dfs(root)
return res
};

后序遍历 左右根#

递归

var postorderTraversal = function(root) {
const res = []
const dfs = (root) => {
if(root === null) return
dfs(root.left)
dfs(root.right)
res.push(root.val)
}
dfs(root)
return res
};

文章分享

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

二叉树的先中后序遍历
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
文章目录