leetcode 二叉树中的最大路径和 && 求和路径 && 二叉树的坡度 && 求根到叶子节点数字之和

94 阅读1分钟

124. 二叉树中的最大路径和

leetcode-cn.com/problems/bi…

  • dfs 后续遍历 如果使用全局记录最大值,只需要在递归的时候 return 当前的一条边(上面提了不能拐),并在函数内部计算以当前节点出发的最大路径和,并更新全局最大值即可。 这里的核心其实是 return 较大的一条边
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxPathSum = function (root) {
    // let res = Math.max(res,Math.max(left,0)+Math.max(right,0)+root.val)
    let res = Number.MIN_SAFE_INTEGER

    const dfs = (root) => {
        if (!root) {
            return 0
        }
        const left = dfs(root.left)
        const right = dfs(root.right)
        res = Math.max(res, Math.max(left, 0) + Math.max(right, 0) + root.val)
        return Math.max(left,right,0) + root.val
    }
    dfs(root)
    return res
};

面试题 04.12. 求和路径

leetcode-cn.com/problems/pa…

  • 双递归
/**
 * @param {TreeNode} root
 * @param {number} sum
 * @return {number}
 */
var pathSum = function (root, sum) {
    let counter = 0

    // 对每一个节点应用dfs
    const preOrder = (root) => {
        if (!root) {
            return
        }
        dfs(root, sum)
        preOrder(root.left)
        preOrder(root.right)
    }

    // 从当前节点出发等于sum
    const dfs = (root, sum) => {
        if (!root) {
            return
        }
        if (sum === root.val) {
            counter++
        }
        dfs(root.left, sum - root.val)
        dfs(root.right, sum - root.val)
    }

    preOrder(root)

    return counter

};

563. 二叉树的坡度

leetcode-cn.com/problems/bi…

  • dfs 后序遍历
/**
 * @param {TreeNode} root
 * @return {number}
 */
var findTilt = function(root) {
    let sum = 0
    const dfs = (root)=>{
        if(!root){
            return 0
        }
        const left = dfs(root.left)
        const right = dfs(root.right)
        sum = sum + Math.abs(left-right)
        return left + right + root.val
    }
    dfs(root)
    
    return sum

};

129. 求根到叶子节点数字之和

leetcode-cn.com/problems/su…

  • dfs 前序遍历
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumNumbers = function(root) {
    let sum = 0

    const dfs = (root,res)=>{
        if(!root){
            return
        }
        res = res * 10 + root.val 
        // 如果是叶子节点
        if(!root.left && !root.right){
            sum = sum +  res
            return
        }
        dfs(root.left,res)
        dfs(root.right,res)
    }
    dfs(root,0)
    return sum
};