先序遍历
中左右
const preorder = root => {if (!root) returnconst stack = [root]while (stack.length) {const n = stack.pop()console.log(n.val);if (n.right) stack.push(n.right) // 注意栈先进后出if (n.left) stack.push(n.left)}}preorder(binaryTree)
中序遍历
左中右
const inorder2 = root => {if (!root) returnconst stack = []let p = rootwhile (stack.length || p) {while (p) {stack.push(p)p = p.left}const n = stack.pop()console.log(n.val);p = n.right}}inorder2(binaryTree)
后序遍历
const postorder2 = root => {if (!root) returnconst outpuStack = []const stack = [root]while (stack.length) {const n = stack.pop()outpuStack.push(n)if (n.left) stack.push(n.left)if (n.right) stack.push(n.right)}while (outpuStack.length) {const n = outpuStack.pop()console.log(n.val);}}postorder2(binaryTree)
