Skip to content

Commit ed74fa0

Browse files
committed
feat: Validate Binary Search Tree
1 parent 23e0bfb commit ed74fa0

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Time complexity: O(n)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @return {boolean}
15+
*/
16+
var isValidBST = function (root) {
17+
const dfs = (root) => {
18+
let minVal = root.val;
19+
let maxVal = root.val;
20+
21+
if (root.left) {
22+
if (root.left.val >= root.val) {
23+
return false;
24+
}
25+
26+
const result = dfs(root.left);
27+
28+
if (!result) {
29+
return false;
30+
}
31+
32+
const [min, max] = result;
33+
34+
if (max >= root.val) {
35+
return false;
36+
}
37+
38+
minVal = Math.min(minVal, min);
39+
maxVal = Math.max(maxVal, max);
40+
}
41+
42+
if (root.right) {
43+
if (root.right.val <= root.val) {
44+
return false;
45+
}
46+
47+
const result = dfs(root.right);
48+
49+
if (!result) {
50+
return false;
51+
}
52+
53+
const [min, max] = result;
54+
55+
if (min <= root.val) {
56+
return false;
57+
}
58+
59+
minVal = Math.min(minVal, min);
60+
maxVal = Math.max(maxVal, max);
61+
}
62+
63+
return [minVal, maxVal];
64+
};
65+
66+
if (dfs(root)) {
67+
return true;
68+
}
69+
70+
return false;
71+
};

0 commit comments

Comments
 (0)