Skip to content

Commit 64d5d07

Browse files
committed
may.12 tree
1 parent a48fe88 commit 64d5d07

4 files changed

Lines changed: 22 additions & 2 deletions

File tree

475 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.

src/Class22_Advanced4/MaximumPathSumBinaryTree2.java

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,28 @@
1313
public class MaximumPathSumBinaryTree2 {
1414
public int maxPathSum(TreeNode root) {
1515
int[] max = new int[]{Integer.MIN_VALUE};
16-
return 0;
16+
if (root == null) {
17+
return Integer.MIN_VALUE;
18+
} else {
19+
max[0] = root.val;
20+
}
21+
helper(root, max);
22+
return max[0];
23+
}
24+
25+
private int helper(TreeNode root, int[] max) {
26+
// TODO Auto-generated method stub
27+
if (root == null) {
28+
return 0;
29+
}
30+
int left = helper(root.left, max);
31+
int right = helper(root.right, max);
32+
33+
// largest subArray sum: dp_class15
34+
left = left < 0 ? 0 : left; // check left path sum. if sum < 0, then don't add it on root
35+
right = right < 0? 0 : right; // check right path sum as above
36+
max[0] = Math.max(max[0], root.val + left + right); //if left == 0 && right == 0, current max == root.val
37+
return root.val + Math.max(left, right); // return largest sum path.
1738
}
1839

1940
public static void main(String[] args) {

src/Class22_Advanced4/MaximumPathSumBinaryTree3.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ private int helper(TreeNode root, int[] max) {
3434

3535
max[0] = Math.max(Math.max(left, right) + root.val, max[0]);
3636
return root.val + Math.max(left, right);
37-
3837
}
3938

4039
public static void main(String[] args) {

0 commit comments

Comments
 (0)