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 3Return 6.
Analysis
1) Recursively solve this problem
2) Get largest left sum and right sum
2) Compare to the stored maximum
public class Solution {
public int maxPathSum(TreeNode root) {
int[] max=new int[1];
max[0]=Integer.MIN_VALUE;
dfs(root,max);
return max[0];
}
private int dfs(TreeNode root,int[] max){
if(root==null)
return 0;
int left=dfs(root.left,max);
int right=dfs(root.right,max);
int cur=Math.max(root.val, Math.max(root.val+left,root.val+right));
max[0]=Math.max(max[0], Math.max(cur, root.val+left+right));
return cur;
}
}