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

二叉树中的最大路径和

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


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

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
     int ans = Integer.MIN_VALUE;
    public int maxPathSum (TreeNode root) {
        // write code here
        if(root == null){
            return 0;
        }
        dfs(root);
        return ans;
    }
    private int dfs(TreeNode root){
        if(root == null){
            return 0;
        }
        //计算左孩子路径最大
        int leftMax = Math.max(dfs(root.left),0);
        //计算右孩子路径最大
        int rightMax = Math.max(dfs(root.right),0);
        ans = Math.max(ans, root.val +leftMax + rightMax);
        
        return root.val + Math.max(leftMax, rightMax);
    }
}
全部评论

相关推荐

能干的三文鱼刷了10...:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 11:35
程序员小白条:话太多,没实力和学历,差不多回答回答就行了,身份地位不一样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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