二叉树的算法在前端面试中还是很重要的,几乎是算法题必问的压轴题,所以弄懂二叉树的遍历算法还是很有必要的,今天我们就来共同探讨一下二叉树的遍历算法。
二叉树的先序遍历算法口诀
- 访问根节点
- 对根节点的左子树进行先序遍历
- 对根节点的右子树进行先序遍历
先序遍历递归版
const bt = {
val: 1,
left: {
val: 2,
left: {
val: 4,
left: null,
right: null
},
right: {
val: 5,
left: null,
right: null
}
},
right: {
val: 3,
left: {
val: 6,
left: null,
right: null
},
right: {
val: 7,
left: null,
right: null
}
}
}
const preorder = (root) => {
if(!root) return
console.log(root.val)
preorder(root.left)
preorder(root.right)
}
preorder(bt)
先序遍历非递归版
//先序遍历非递归版
const preorder2 = (root) => {
if(!root) return
const stack = [root]
while(stack.length) {
const n = stack.pop()
console.log(n)
n.right && stack.push(n.right)
n.left && stack.push(n.left)
}
}
中序遍历算法口诀
- 对根节点的左子树进行中序遍历
- 访问根节点
- 对根节点的右子树进行中序遍历
中序遍历递归版
const inorder = (root) => {
if(!root) return
inorder(root.left)
console.log(root.val)
inorder(root.right)
}
中序遍历非递归版
const inorder2 = (root) => {
if(!root) return
const stack = []
let p = root //定义一个指针,先指向根节点
while(stack.length || p) {
while(p) { //先把左子树都推入栈
stack.push(p)
p = p.left
}
const 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 postorder2 = (root) => {
if(!root) return
const stack = [root]
const outputStack = []
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()
console.log(n.val)
}
}
总结
递归版的遍历比较容易有思路去实现,那其实非递归版的遍历其实只是改成了栈的方式,但其实是一样的,因为在函数里调用另一个函数,本身就会形成函数调用堆栈,每执行完一个函数就释放一个。所以我们的最终实现是用堆栈模拟递归的过程。