题解 | #二叉树的最大路径和#

二叉树的最大路径和

http://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a

import java.util.*;

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

public class Solution {

    private int max;
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxPathSum (TreeNode root) {
        // write code here
        max = Integer.MIN_VALUE;
        maxPathDown(root);
        return max;
    }

    private int maxPathDown(TreeNode node) {
        if (node == null) return 0;
        int left = Math.max(0,maxPathDown(node.left));
        int right = Math.max(0,maxPathDown(node.right));
        max = Math.max(max,left + right + node.val);
        return Math.max(left,right) + node.val;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-29 17:30
点赞 评论 收藏
分享
06-07 19:59
门头沟学院 C++
补药卡我啊😭:都快15年前的了还在11新特性
你的简历改到第几版了
点赞 评论 收藏
分享
LemontreeN:有的兄弟有的我今天一天面了五场,4个二面一个hr面
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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