二叉树深度优先 之 先中后序遍历
昨天刷了 leetcode 上面有关二叉树的三个遍历问题。 总结一下各自 非递归(迭代) 的算法。
- 二叉树的遍历
- 广度 优先遍历
- 深度 优先遍历
- 先 序遍历 => 根 - 左 - 右
- 中 序遍历 => 左 - 根 - 右
- 后 序遍历 => 左 - 右 - 根
先序遍历
应用:
打印一个结构化文档
思路如下
代码
var preorderTraversal = function(root) {
const stack = []
const res = []
if (root) {stack.push(root)}
while (stack.length) {
const n = stack.pop()
res.push(n.val)
if(n.right) stack.push(n.right)
if(n.left) stack.push(n.left)
}
return res
};
中序遍历
应用:
对数进行排队操作
思路如下
代码
var inorderTraversal = function(root) {
const stack = []
const res = []
let p = root
while (stack.length || p) {
while (p) {
stack.push(p)
p = p.left
}
const n = stack.pop()
res.push(n.val)
p = n.right
}
return res
};
后序遍历
应用:
计算一个目录及其子目录中所以文件所占空间大小
思路如下
代码
var postorderTraversal = function(root) {
const res = []
const stack = []
const outputStack = []
if (root) stack.push(root)
while (stack.length) {
const n = stack.pop()
outputStack.push(n)
n.left && stack.push(n.left)
n.right && stack.push(n.right)
}
while (outputStack.length) {
const n = outputStack.pop()
res.push(n.val)
}
return res
};