-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlk1373.java
48 lines (45 loc) · 1.19 KB
/
lk1373.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
43
44
45
46
47
48
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int maxSum = 0;
public int maxSumBST(TreeNode root) {
traverse(root);
return maxSum;
}
// 函数返回 int[]{ isBST, min, max, sum}
int[] traverse(TreeNode root) {
// base case
if (root == null) {
return new int[]{
1, Integer.MAX_VALUE, Integer.MIN_VALUE, 0
};
}
int[] left = traverse(root.left);
int[] right = traverse(root.right);
int[] res = new int[4];
if (left[0] == 1 && right[0] == 1 &&
root.val > left[2] && root.val < right[1]) {
res[0] = 1;
res[1] = Math.min(left[1], root.val);
res[2] = Math.max(right[2], root.val);
res[3] = left[3] + right[3] + root.val;
maxSum = Math.max(maxSum, res[3]);
} else {
res[0] = 0;
}
return res;
}
}