zoukankan      html  css  js  c++  java
  • Hard | LeetCode 124. 二叉树中的最大路径和

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

    路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径 至少包含一个 节点,且不一定经过根节点。

    路径和 是路径中各节点值的总和。

    给你一个二叉树的根节点 root ,返回其 最大路径和

    示例 1:

    img
    输入:root = [1,2,3]
    输出:6
    解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
    

    示例 2:

    img
    输入:root = [-10,9,20,null,null,15,7]
    输出:42
    解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
    

    提示:

    • 树中节点数目范围是 [1, 3 * 104]
    • -1000 <= Node.val <= 1000

    解题思路

    此题和 Easy | LeetCode 543. 二叉树的直径 类型。不过那道题是只要直径, 而本题是要取其值。思路都是一致的, 都是左子树的和 + 右子树的和。

    class Solution {
    
        private int res = Integer.MIN_VALUE;
    
        public int maxPathSum(TreeNode root) {
            getRootSum(root);
            return res;
        }
    
        public int getRootSum(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int leftValue = getRootSum(root.left);
            int rightValue = getRootSum(root.right);
            res = Math.max(res, (Math.max(0, leftValue) + Math.max(0, rightValue) + root.val));
            return root.val + Math.max(Math.max(0, leftValue), Math.max(0, rightValue));
        }
    }
    
  • 相关阅读:
    [转]难过的时候看看,也许会豁然开朗
    热爱生活
    [转]MTOM 编码
    11/16
    11/10 The Day Before Single's Day
    About working overtime
    hehe
    The First Blog
    配置MapServer出现的一些问题及解决办法
    Ubuntu 系统下终端快捷键设置
  • 原文地址:https://www.cnblogs.com/chenrj97/p/14293307.html
Copyright © 2011-2022 走看看