Skip to content

Commit a01fa0a

Browse files
committed
solve: validate binary search tree
1 parent 0501468 commit a01fa0a

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* TC: O(N)
3+
* SC: O(N)
4+
* N: total count of tree nodes
5+
*/
6+
7+
/**
8+
* Definition for a binary tree node.
9+
* function TreeNode(val, left, right) {
10+
* this.val = (val===undefined ? 0 : val)
11+
* this.left = (left===undefined ? null : left)
12+
* this.right = (right===undefined ? null : right)
13+
* }
14+
*/
15+
/**
16+
* @param {TreeNode} root
17+
* @return {boolean}
18+
*/
19+
var isValidBST = function (root) {
20+
return isValidBSTWithBoundary(
21+
root,
22+
Number.MIN_SAFE_INTEGER,
23+
Number.MAX_SAFE_INTEGER
24+
);
25+
26+
function isValidBSTWithBoundary(current, min, max) {
27+
if (!current) {
28+
return true;
29+
}
30+
31+
if (current.val <= min || max <= current.val) {
32+
return false;
33+
}
34+
35+
return (
36+
isValidBSTWithBoundary(current.left, min, current.val) &&
37+
isValidBSTWithBoundary(current.right, current.val, max)
38+
);
39+
}
40+
};

0 commit comments

Comments
 (0)