先序遍历: 根节点-》左子树-》右子树
const preorder = (root) => {
if(!root) return
console.log(root.val)
preorder(root.left)
preorder(root.right)
}
先序遍历非递归版
const preorder = (root) => {
if(!root) return
const stack = [root]
while(stack.length) {
const n = stack.pop()
console.log(n.value)
if(n.right) stack.push(n.right)
if(n.left) stack.push(n.left)
}
}
中序遍历 左子树-》根结点-》右子树
function inorder (root) {
if(!root) return;
preorder(root.left)
console.log(root.val)
preorder(root.right)
}
非递归版本
function inorder(root) {
if(!root) return;
const stack = []
const p = root
while(stack.length || p) {
while(p) {
stack.push(p)
p = p.left
}
const n = stack.pop()
console.log(n.val)
p = p.right
}
}
后序遍历: 右子树 =》 根节点 =》 左子树
const postOrder = (root) => {
if(!root) return;
postOrder(root.right)
console.log(root.value)
preOrder(root.left)
}
后序遍历非递归
const postOrder = (root) => {
if(!root) return
const stack = [root]
const outputStack = []
while(stack.lenght) {
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)
}
}