Skip to content

Commit ff7777f

Browse files
Lintcode/src/chapter3_binary_tree_and_divide_and_conquer/BinaryTreeMaximumPathSumII.java
1 parent 49cfd42 commit ff7777f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package chapter3_binary_tree_and_divide_and_conquer;
2+
3+
import classes.TreeNode;
4+
5+
public class BinaryTreeMaximumPathSumII {
6+
7+
/**
8+
* @param root the root of binary tree.
9+
* @return an integer
10+
*/
11+
int max = Integer.MIN_VALUE;
12+
public int maxPathSum2(TreeNode root) {
13+
// Write your code here
14+
if(root == null) return 0;
15+
return dfs(root, 0, max);
16+
}
17+
18+
int dfs(TreeNode root, int curr, int max){
19+
curr += root.val;
20+
max = Math.max(max, curr);
21+
int leftMax = max, rightMax = max;
22+
if(root.left != null) leftMax = dfs(root.left, curr, max);
23+
if(root.right != null) rightMax = dfs(root.right, curr, max);
24+
return Math.max(Math.max(leftMax, rightMax), max);
25+
}
26+
27+
public static void main(String...strings){
28+
BinaryTreeMaximumPathSumII test = new BinaryTreeMaximumPathSumII();
29+
TreeNode root = new TreeNode(1);
30+
root.left = new TreeNode(2);
31+
root.right = new TreeNode(3);
32+
System.out.print(test.maxPathSum2(root));
33+
}
34+
35+
}

0 commit comments

Comments
 (0)