[LeetCode]Binary Tree Maximum Path Sum, 解题报告

2014-11-24 12:48:03 · 作者: · 浏览: 4

题目

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

vc+88rWlo6zS1Nfz19PK98K3vra6zc6qwP2jrLXDtb3X89fTyvfCt762us2+38zlJiMyMDU0MDu687rNMNf2sci9z6OsPCAwINTyt7W72DAsID4w1PK3tbvYvt/M5SYjMjA1NDA7Cjxicj4KCqOoMqOpzqrKssO0t7W72LXETUFYIHu1scewvdq14yAmIzQzOyDX89fTyvfCt762us2jrCC1scewvdq14yAmIzQzOyDT0tfTyvfCt762us19o6y2+LK7yse3tbvYeyC1scewvdq14yYjNDM71/PX08r3wre+trrNICYjNDM7INPS19PK98K3vra6zSB9o78KPGJyPgoK0vLOqtXiwO/Ct762srvE3LTm1NrW2Li0vdq146Ostv6y5sr3wre+trXEtqjS5crHw7+49r3atePWu8Tct8POytK7tM6jrMjnufu3tbvYtcTKx3sgtbHHsL3ateMmIzQzO9fz19PK98K3vra6zSAmIzQzOyDT0tfTyvfCt762us0gfaOs1PKx2Mi7tObU2sSz0rvP4LbUuPm92rXjtuC0zrfDzsq1xMfpv/ajrMq+wP22/rLmyve94bm5yOfPwqO6CjxpbWcgc3JjPQ=="https://www.cppentry.com/upload_files/article/49/1_fjxne__.png" alt="\">
以节点2为例,返回到根节点1的值应该为2+5=7,而不是2+4+5=11,因为2只能访问一次

AC代码

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private static int maxValue;
    
    public static int maxPathSum(TreeNode root) {
        maxValue = root == null   0 : root.val;
        findPath(root);
        return maxValue;
    }
    
    public static int findPath(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int left = Math.max(findPath(root.left), 0);
        int right = Math.max(findPath(root.right), 0);
        
        maxValue = Math.max(maxValue, root.val + left + right);
        
        int current = Math.max(root.val, Math.max(root.val + left, root.val + right));
                
        return current;
    }
}