1
+ // Runtime: 347 ms (Top 18.00%) | Memory: 83.8 MB (Top 70.00%)
2
+
1
3
var maxSumBST = function ( root ) {
2
4
let max = 0 ;
3
5
const dfs = ( node ) => {
4
- // NoNode
6
+ // NoNode
5
7
if ( ! node ) return [ true , 0 , Infinity , - Infinity ] ;
6
8
7
- // LeafNode
9
+ // LeafNode
8
10
if ( node && ! node . left && ! node . right ) {
9
11
max = Math . max ( max , node . val ) ;
10
12
return [ true , node . val , node . val , node . val ]
@@ -13,30 +15,30 @@ var maxSumBST = function(root) {
13
15
const [ isLeftValid , leftVal , leftMin , leftMax ] = dfs ( node . left ) ;
14
16
const [ isRightValid , rightVal , rightMin , rightMax ] = dfs ( node . right ) ;
15
17
16
- /**
17
- * To establish that the current node is also a valid BST, we need to verify the following:
18
- * 1. Left sub tree is a valid BST
19
- * 2. Right sub tree is a valid BST
20
- * 3. The values in the left BST are smaller than current node's value
21
- * 4. The values in the right BST are greater than current node's value
22
- **/
18
+ /**
19
+ * To establish that the current node is also a valid BST, we need to verify the following:
20
+ * 1. Left sub tree is a valid BST
21
+ * 2. Right sub tree is a valid BST
22
+ * 3. The values in the left BST are smaller than current node's value
23
+ * 4. The values in the right BST are greater than current node's value
24
+ **/
23
25
if ( isLeftValid && isRightValid && node . val > leftMax && node . val < rightMin ) {
24
26
max = Math . max ( max , leftVal + rightVal + node . val ) ;
25
27
return [
26
28
true ,
27
29
leftVal + rightVal + node . val ,
28
- /**
29
- * 12
30
- * / \
31
- * 8 16
32
- * \ /
33
- * 9 15
34
- * \ /
35
- * 10 14
36
- * \ /
37
- * Infinity -Infinity
38
- * [Infinity and -Infinity are to depict NoNode cases]
39
- **/
30
+ /**
31
+ * 12
32
+ * / \
33
+ * 8 16
34
+ * \ /
35
+ * 9 15
36
+ * \ /
37
+ * 10 14
38
+ * \ /
39
+ * Infinity -Infinity
40
+ * [Infinity and -Infinity are to depict NoNode cases]
41
+ **/
40
42
Math . min ( node . val , leftMin ) ,
41
43
Math . max ( node . val , rightMax )
42
44
] ;
@@ -47,4 +49,4 @@ var maxSumBST = function(root) {
47
49
dfs ( root ) ;
48
50
49
51
return max ;
50
- } ;
52
+ } ;
0 commit comments