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

二叉树中的最大路径和

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

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    int res = Integer.MIN_VALUE;
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxPathSum (TreeNode root) {
        // write code here
        maxPathSum2(root);
        return res;
    }
    public int maxPathSum2 (TreeNode root) {
        // write code here
        if (root==null) return 0;
        int l = maxPathSum2(root.left);
        int r = maxPathSum2(root.right);
        res = Math.max(res, root.val);
        res = Math.max(res, root.val+l);
        res = Math.max(res, root.val+r);
        res = Math.max(res, root.val+r+l);
        return Math.max(Math.max(root.val, l+root.val), r+root.val);
    }
}

全部评论

相关推荐

牛客76783384...:字节:不要放箭,活捉赵子龙
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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