从迭代和递归去实现二叉树遍历

41 阅读1分钟

前序遍历

var preorderTraversal = function(root) {
    // 迭代思想
     const stack = [root]
     let res = []
     if(!root){return []}
     while(stack.length){
         root = stack.pop()
         res.push(root.val)
        root.right && stack.push(root.right)
          root.left && stack.push(root.left)
          }
     return res

    // 递归思想
    let res= []
    const qx = function(root){
        if(!root){return}
        res.push(root.val)
        qx(root.left)
        qx(root.right)
    }
    qx(root)
    return res
};

中序遍历

var inorderTraversal = function(root) {
    //栈的思想  迭代法
     const stack = []
     const res = []
     while(stack.length || root){
         if(root){
             stack.push(root)
             root = root.left
        }else{
            let o = stack.pop()
            res.push(o.val)
             root= o.right
         }
     }
     return res

    // 递归思想
    const res = []
    const zx = function(root){
        if(!root){
            return
        }
        zx(root.left)
        res.push(root.val)
        zx(root.right)    
    }
    zx(root)
    return res
};

后序遍历

var postorderTraversal = function(root) {
     递归思想
     let res = []
     const hx = function(root){
         if(!root) return
        hx(root.left)
        hx(root.right)
        res.push(root.val)
    }
     hx(root)
     return res


    //迭代思想
    let stack = [root]
    let res = []
    if(!root){ return []}
    while(stack.length){
        let a = stack.pop()
        res.push(a.val)
        a.left && stack.push(a.left)
        a.right && stack.push(a.right)
    }
    return res.reverse()
};