File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * public class TreeNode {
4
+ * int val;
5
+ * TreeNode left;
6
+ * TreeNode right;
7
+ * TreeNode() {}
8
+ * TreeNode(int val) { this.val = val; }
9
+ * TreeNode(int val, TreeNode left, TreeNode right) {
10
+ * this.val = val;
11
+ * this.left = left;
12
+ * this.right = right;
13
+ * }
14
+ * }
15
+ */
16
+ class Solution {
17
+ public int maxSumBST (TreeNode root ) {
18
+ int [] ans = {0 };
19
+ helper (root , ans );
20
+ return ans [0 ];
21
+ }
22
+
23
+ private int [] helper (TreeNode root , int [] ans ) {
24
+ if (root == null ) {
25
+ // new int[]{min, max, sum}
26
+ return new int []{Integer .MAX_VALUE , Integer .MIN_VALUE , 0 };
27
+ }
28
+ int [] left = helper (root .left , ans );
29
+ int [] right = helper (root .right , ans );
30
+ if (!(left != null && right != null && root .val > left [1 ] && root .val < right [0 ])) {
31
+ return null ;
32
+ }
33
+ int sum = root .val + left [2 ] + right [2 ];
34
+ ans [0 ] = Math .max (ans [0 ], sum );
35
+ int min = Math .min (root .val , left [0 ]);
36
+ int max = Math .max (root .val , right [1 ]);
37
+ return new int []{min , max , sum };
38
+ }
39
+ }
You can’t perform that action at this time.
0 commit comments