Skip to content

Commit 1977bab

Browse files
committed
Add week 7 solutions : validateBinarySearchTree
1 parent 0ce8e58 commit 1977bab

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(n)
3+
4+
var isValidBST = function (root) {
5+
if (root === null) {
6+
return true;
7+
}
8+
9+
// initialize a queue for BFS.
10+
let queue = [];
11+
queue.push({ node: root, min: -Infinity, max: Infinity });
12+
13+
while (queue.length > 0) {
14+
// dequeue the front one.
15+
let { node, min, max } = queue.shift();
16+
17+
// check the BST for the current node.
18+
if (node.val <= min || node.val >= max) {
19+
return false;
20+
}
21+
22+
// enqueue the left child with updated min and max.
23+
if (node.left !== null) {
24+
queue.push({ node: node.left, min: min, max: node.val });
25+
}
26+
27+
// enqueue the right child with updated min and max.
28+
if (node.right !== null) {
29+
queue.push({ node: node.right, min: node.val, max: max });
30+
}
31+
}
32+
33+
return true;
34+
};

0 commit comments

Comments
 (0)