let tree = {
val: 5,
left: {
val: 2,
left: {
val: 1,
left: null,
right: null
},
right: {
val: 4,
left: {
val: 3,
left: null,
right: null
},
right: null
}
},
right: {
val: 6,
left: null,
right: {
val: 7,
left: null,
right: null
}
}
}
function inorder(root) {
console.log('中序遍历');
if (!root) return
let stack = []
let p = root
while (stack.length || p) {
while (p) {
stack.push(p)
p = p.left
}
let curNode = stack.pop()
console.log(curNode.val)
p = curNode.right
}
}
inorder(tree)
function preorder(root) {
console.log('前序遍历');
if (!root) return
let stack = [root]
while (stack.length) {
let curNode = stack.pop()
console.log(curNode.val)
if (curNode.right) stack.push(curNode.right)
if (curNode.left) stack.push(curNode.left)
}
}
preorder(tree)
function postorder(root) {
console.log('后序遍历');
if (!root) return
let stack = [root]
let outputStack = []
while (stack.length) {
let curNode = stack.pop()
outputStack.push(curNode)
if (curNode.left) stack.push(curNode.left)
if (curNode.right) stack.push(curNode.right)
}
while (outputStack.length) {
console.log(outputStack.pop().val)
}
}
postorder(tree)
