Skip to content

Commit c243ab3

Browse files
committed
Binary Tree Maximum Path Sum
1 parent b8b8ed5 commit c243ab3

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// TC: O(n)
2+
// visit all nodes to find maximum path
3+
// SC: O(h)
4+
// h means the high of binary tree
5+
class Solution {
6+
private int output = Integer.MIN_VALUE;
7+
public int maxPathSum(TreeNode root) {
8+
max(root);
9+
return output;
10+
}
11+
12+
private int max(TreeNode node) {
13+
if (node == null) return 0;
14+
15+
int leftSum = Math.max(max(node.left), 0);
16+
int rightSum = Math.max(max(node.right), 0);
17+
18+
int currentMax = node.val + leftSum + rightSum;
19+
20+
output = Math.max(output, currentMax);
21+
22+
return node.val + Math.max(leftSum, rightSum);
23+
}
24+
}

0 commit comments

Comments
 (0)