题目:
难度级别: ★★★
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,
1 / \ 2 3
Return 6
.
思路:
暂略
代码:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
static int max;
public int maxPathSum(TreeNode root) {
if (root == null){
return 0;
}
max = root.val;
getPathSum(root);
return max;
}
static int getPathSum(TreeNode root){
if (root == null){
return 0;
}
int lsum,rsum;
int sum = root.val;
lsum = getPathSum(root.left);
rsum = getPathSum(root.right);
//find the max sum from left child to right child via root, compare the result with max
if (lsum > 0){
sum += lsum;
}
if (rsum > 0){
sum += rsum;
}
if (sum > max){
max = sum;
}
//choose either or neither of rsum and lsum, plus root.val as the result to return to the up level
if (rsum > 0 && rsum >= lsum){
return rsum + root.val;
}else if (lsum > 0 && lsum >= rsum){
return lsum + root.val;
}
return root.val;
}
}