forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1373.java
More file actions
27 lines (23 loc) · 761 Bytes
/
1373.java
File metadata and controls
27 lines (23 loc) · 761 Bytes
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
class Solution {
public int maxSumBST(TreeNode root) {
dfs(root);
return maxv;
}
private int maxv = 0;
private int[] dfs(TreeNode root) {
if (root == null) return new int[]{1, 0};
int[] res = new int[]{1, root.val};
if (root.left != null) {
int[] left = dfs(root.left);
if (left[0] == 1 && root.left.val < root.val) res[1] += left[1];
else res[0] = 0;
}
if (root.right != null) {
int[] right = dfs(root.right);
if (right[0] == 1 && root.right.val > root.val) res[1] += right[1];
else res[0] = 0;
}
if (res[0] == 1) maxv = Math.max(maxv, res[1]);
return res;
}
}