Skip to content

Commit 09d2fe5

Browse files
committed
Runtime: 347 ms (Top 18.00%) | Memory: 83.8 MB (Top 70.00%)
1 parent 3ee34f9 commit 09d2fe5

File tree

1 file changed

+24
-22
lines changed

1 file changed

+24
-22
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
// Runtime: 347 ms (Top 18.00%) | Memory: 83.8 MB (Top 70.00%)
2+
13
var maxSumBST = function(root) {
24
let max = 0;
35
const dfs = (node) => {
4-
// NoNode
6+
// NoNode
57
if(!node) return [true, 0, Infinity, -Infinity];
68

7-
// LeafNode
9+
// LeafNode
810
if(node && !node.left && !node.right) {
911
max = Math.max(max, node.val);
1012
return [true, node.val, node.val, node.val]
@@ -13,30 +15,30 @@ var maxSumBST = function(root) {
1315
const [isLeftValid, leftVal, leftMin, leftMax] = dfs(node.left);
1416
const [isRightValid, rightVal, rightMin, rightMax] = dfs(node.right);
1517

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+
**/
2325
if(isLeftValid && isRightValid && node.val > leftMax && node.val < rightMin) {
2426
max = Math.max(max, leftVal + rightVal + node.val);
2527
return [
2628
true,
2729
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+
**/
4042
Math.min(node.val, leftMin),
4143
Math.max(node.val, rightMax)
4244
];
@@ -47,4 +49,4 @@ var maxSumBST = function(root) {
4749
dfs(root);
4850

4951
return max;
50-
};
52+
};

0 commit comments

Comments
 (0)