写在前面: 前中后序遍历三种遍历方式基于迭代和非迭代写法是面试中常考点,这里做一下总结
前序遍历
定义: 对二叉树的遍历遵循先遍历root, 再遍历root.left, 最后遍历root.right
- 前序遍历的递归写法
const preOrder = (root) => {
if(!root) return
console.log(root.val)
preOrder(root.left)
preOrder(root.right)
}
- 前序遍历的非递归写法
const preOrder = (root) => {
if(!root) return
let stack = [root]
while(stack.length) {
let n = stack.pop();
console.log(n.val);
if(n.right) stack.push(n.right)
if(n.left) stack.push(n.left)
}
}
中序遍历
定义:对二叉树的遍历先遍历树的左子树,然后再获取左子树的父节点,然后再遍历其右子树
- 中序遍历的递归写法
const inOrder = (root) => {
if(!root) return
if(root.left) inOrder(root.left)
console.log(root.val)
if(root.right) inOrder(root.right)
}
- 中序遍历的非递归写法
const inOrder = (root) => {
if (!root) return
let stack = [];
let p = root;
while(stack.length || p) {
while(p) {
stack.push(p)
p = p.left
}
let n = stack.pop();
console.log(n.val)
p = n.right
}
}
后续遍历
定义: 对二叉树的遍历先遍历其左子树,然后遍历左子树的右子树,然后遍历左子树的父节点
- 后续遍历的递归写法
const postOrder = (root) => {
if(!root) return
postOrder(root.left);
postOrder(root.right);
console.log(root.val)
}
- 后续遍历的非递归写法
const postOrder = (root) => {
if(!root) return
let outputStack = [];
let stack = [root]
while(stack.length) {
const n = stack.pop();
outputStack.push(n);
if(n.left) stack.push(n.left)
if(n.right) stack.push(n.right)
}
while(outputStack.length) {
const n = outputStack.pop();
console.log(n.val)
}
}