Problem:
Analysis:
In this problem, I gonna use DFS to solve it. By using recursion, we should set up the base rule and recursive rule.
there is a small trick in this problem, we should pass the int[] not a int, since java pass value. we need an array to wrap the integer.
Code:
public int maxPathSum(TreeNode root) {
if (root == null){
return 0;
}
int[] k = new int[]{Integer.MIN_VALUE};
dfs(root, k);
return k[0];
}
private int dfs(TreeNode root, int[] k){
// base leaf node, --> null?
// recursion rull
int left = root.left == null? 0 : Math.max(dfs(root.left, k), 0);
int right = root.right == null? 0: Math.max(dfs(root.right, k), 0);
int cur = root.val + left + right;
k[0] = Math.max(k[0], cur);
return root.val + Math.max(right, left);
}