首页 > 其他 > 详细

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

时间:2021-06-04 17:51:46      阅读:11      评论:0      收藏:0      [点我收藏+]

简介

理解题目很重要
注意,不能走进一个分支又掉头回来走另一个分支,路径会重叠,不符合定义。

code

class Solution {
    public int maxValue = Integer.MIN_VALUE;
    public int maxPath(TreeNode root) {
        if(root == null) return 0;
        int leftValue = 0;
        int rightValue = 0;
        if(root.left != null) leftValue = Math.max(maxPath(root.left), 0);
        if(root.right != null) rightValue = Math.max(maxPath(root.right), 0);

        int pathValue = leftValue + rightValue + root.val;
        if(maxValue < pathValue) maxValue = pathValue;
        return root.val + Math.max(rightValue, leftValue); // 路径值 单边传递.
    }
    public int maxPathSum(TreeNode root){
        maxPath(root);
        return maxValue;
    }
}

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

原文:https://www.cnblogs.com/eat-too-much/p/14849450.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!