Skip to content

Commit 4763cfc

Browse files
committed
Add validate-binary-search-tree solution
1 parent 6923dd6 commit 4763cfc

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// ✅ Time Complexity: O(N), where N is the number of nodes in the tree.
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+
// Helper function to check BST validity
18+
const dfs = (node, low, high) => {
19+
// Base case: Empty subtree is valid
20+
if (!node) return true;
21+
22+
if (!(low < node.val && node.val < high)) return false;
23+
24+
return dfs(node.left, low, node.val) && dfs(node.right, node.val, high);
25+
};
26+
27+
return dfs(root, -Infinity, Infinity);
28+
};
29+

0 commit comments

Comments
 (0)