day14 - 二叉树的前中后遍历 - 递归法,迭代法

68 阅读1分钟

144.二叉树的前序遍历

  1. 递归法
var preorderTraversal = function(root) {
    //前序遍历 :中 -> 左 -> 右
    let res = []
    function dfs(root){
        if(!root) return
        res.push(root.val)
        dfs(root.left)
        dfs(root.right)
    }
    dfs(root)
    return res
}
  1. 迭代法
var preorderTraversal = function(root) {
    //前序遍历 :中 -> 左 -> 右
    if(!root) return []
    let res = []
    let stack = [root]

    while(stack.length){
        let node = stack.pop()
        res.push(node.val)
        // 先入后出,所以先push右子树,再push左子树
        node.right && stack.push(node.right)
        node.left && stack.push(node.left)
    }
    return res
}

145.二叉树的后序遍历

  1. 递归法
var inorderTraversal = function(root) {
    // 中序遍历 : 左->中->右
    let res = []
    function dfs(root){
        if(!root) return 
        dfs(root.left)
        res.push(root.val)
        dfs(root.right)
    }
    dfs(root)
    return res

};
  1. 迭代法
var inorderTraversal = function(root) {
    // 左 -> 中 -> 右
    if(!root) return []
    let stack = []
    let res = []

    let cur = root
    while(stack.length || cur){
        while(cur){
            stack.push(cur)
            cur = cur.left
        }
        let node = stack.pop()
        res.push(node.val)
        if(node.right){
            cur = node.right
        }
    }
    return res
};

94.二叉树的中序遍历

  1. 递归法
var postorderTraversal = function(root) {
    // 后序遍历  左 -> 右 -> 中
    const res = []

    function dfs(root){
        if(!root) return
        dfs(root.left)
        dfs(root.right)
        res.push(root.val)
    }

    dfs(root)
    return res
};
  1. 迭代法
var postorderTraversal = function(root) {
    if(!root) return []
    // 后序遍历  左 -> 右 -> 中
    const res = []
    const stack = [root]

    while(stack.length){
        let node = stack.pop()
        res.push(node.val)
        //思路是按照 中->右->左 的顺序进行遍历
        //在 push 的时候先左后右 ,结果是先右后左
        node.left && stack.push(node.left)
        node.right && stack.push(node.right)
    }

    return res.reverse()
};