每天刷一道牛客题霸-第13天-二叉树的最大路径和

题目

https://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a?tpId=190&rp=1&ru=%2Fta%2Fjob-code-high-rd&qru=%2Fta%2Fjob-code-high-rd%2Fquestion-ranking

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public static int maxValue;

    public int maxPathSum (TreeNode root) {
        // write code here
        maxValue = Integer.MIN_VALUE;
        getMaxPathSum(root);
        return maxValue;
    }
    public int getMaxPathSum(TreeNode root){
        if(root != null){
            int maxLeftValue = Math.max(0,getMaxPathSum(root.left));
            int maxRightValue = Math.max(0,getMaxPathSum(root.right));
            maxValue = Math.max(maxValue,maxLeftValue + root.val + maxRightValue);
            return Math.max(maxLeftValue , maxRightValue)+ root.val;
        }
        return 0;
    }
}
#牛客题霸##题解#
全部评论
这道题算hard题吗?
点赞 回复 分享
发布于 2020-12-17 00:28
点赞 回复 分享
发布于 2020-12-16 20:50

相关推荐

06-05 19:46
已编辑
武汉大学 后端
点赞 评论 收藏
分享
06-12 16:00
天津大学 Java
牛客30236098...:腾讯坏事做尽,终面挂是最破防的 上次被挂了后我连简历都不刷了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务