先序遍历: 根节点-》左子树-》右子树

    1. const preorder = (root) => {
    2. if(!root) return
    3. console.log(root.val)
    4. preorder(root.left)
    5. preorder(root.right)
    6. }

    先序遍历非递归版

    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.value)
    7. if(n.right) stack.push(n.right)
    8. if(n.left) stack.push(n.left)
    9. }
    10. }

    中序遍历 左子树-》根结点-》右子树

    1. function inorder (root) {
    2. if(!root) return;
    3. preorder(root.left)
    4. console.log(root.val)
    5. preorder(root.right)
    6. }

    非递归版本

    1. function inorder(root) {
    2. if(!root) return;
    3. const stack = []
    4. const 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 = p.right
    13. }
    14. }

    后序遍历: 右子树 =》 根节点 =》 左子树

    1. const postOrder = root) => {
    2. if(!root) return;
    3. postOrder(root.right)
    4. console.log(root.value)
    5. preOrder(root.left)
    6. }

    后序遍历非递归

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