Skip to content

Commit bf6bdeb

Browse files
committed
solve binary tree maximum path sum
1 parent af05c08 commit bf6bdeb

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
public class Solution {
2+
private int maxSum;
3+
4+
public int maxPathSum(TreeNode root) {
5+
maxSum = root.val;
6+
dfs(root);
7+
return maxSum;
8+
}
9+
10+
private int dfs(TreeNode node) {
11+
if (node == null) {
12+
return 0;
13+
}
14+
15+
int leftMax = Math.max(dfs(node.left), 0);
16+
int rightMax = Math.max(dfs(node.right), 0);
17+
18+
maxSum = Math.max(maxSum, node.val + leftMax + rightMax);
19+
20+
return node.val + Math.max(leftMax, rightMax);
21+
}
22+
}
23+

0 commit comments

Comments
 (0)