題目
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=="http://www.2cto.com/uploadfile/Collfiles/20140511/20140511092309181.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;
}
}