先序遍历

中左右

  1. const preorder = root => {
  2. if (!root) return
  3. const stack = [root]
  4. while (stack.length) {
  5. const n = stack.pop()
  6. console.log(n.val);
  7. if (n.right) stack.push(n.right) // 注意栈先进后出
  8. if (n.left) stack.push(n.left)
  9. }
  10. }
  11. preorder(binaryTree)

中序遍历

左中右

  1. const inorder2 = root => {
  2. if (!root) return
  3. const stack = []
  4. let p = root
  5. while (stack.length || p) {
  6. while (p) {
  7. stack.push(p)
  8. p = p.left
  9. }
  10. const n = stack.pop()
  11. console.log(n.val);
  12. p = n.right
  13. }
  14. }
  15. inorder2(binaryTree)

后序遍历

  1. const postorder2 = root => {
  2. if (!root) return
  3. const outpuStack = []
  4. const stack = [root]
  5. while (stack.length) {
  6. const n = stack.pop()
  7. outpuStack.push(n)
  8. if (n.left) stack.push(n.left)
  9. if (n.right) stack.push(n.right)
  10. }
  11. while (outpuStack.length) {
  12. const n = outpuStack.pop()
  13. console.log(n.val);
  14. }
  15. }
  16. postorder2(binaryTree)