Problem
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
.
Solution
public class Solution {
int ans;
public int maxPathSum(TreeNode root) {
ans=root.val;
search(root);
return ans;
}
public int search(TreeNode root){
int res=root.val;
int left=0,right=0;
if(root.left!=null){
left=search(root.left);
if(left>ans)ans=left;
if(left>0){
res+=left;
}
}
if(root.right!=null){
right=search(root.right);
if(right>ans)ans=right;
if(right>0){
res+=right;
}
}
if(res>ans)ans=res;
int sum=root.val;
int maxVal=Math.max(left, right);
if(maxVal>0)sum+=maxVal;
return sum;
}
public static void main(String[] args) {
Solution sln = new Solution();
}
}
思路
search函数返回以root以根的树上面从root出发的Maximum Path Sum,也就是说这个Path要么在root的左子树,要么在右子树,不会跨过左右子树。
开始时在search函数中返回了以root为根的树上的Maximum Path Sum,允许Path同时在左右子树上,这种做法在求当前树的Maximum Path Sum时是对的,但是返回到上一层的值是没意义的,因为当上一层的节点连接到当前的root节点时已经不是题目要求的Path了。