-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution124.java
42 lines (33 loc) · 954 Bytes
/
Solution124.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package leetcode.tree.postorder;
import leetcode.TreeNode;
public class Solution124 {
public static void main(String[] args) {
TreeNode node = new TreeNode(2);
node.left = new TreeNode(1);
node.right = new TreeNode(3);
System.out.println(new Solution124().maxPathSum(node));
}
int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
doMaxPathSum(root);
return res;
}
private int doMaxPathSum(TreeNode node) {
if (node == null) {
return 0;
}
int left = doMaxPathSum(node.left);
int right = doMaxPathSum(node.right);
int cur = node.val, max = node.val;
if (left > 0) {
cur += left;
max += left;
}
if (right > 0) {
cur += right;
max = Math.max(max, node.val + right);
}
res = Math.max(res, cur);
return max;
}
}