-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate-binary-search-tree.js
47 lines (38 loc) · 1.1 KB
/
validate-binary-search-tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
Validate Binary Search Tree (https://leetcode.com/problems/validate-binary-search-tree/)
- Given the root of a binary tree, determine if it is a valid binary search tree (BST)
Definition of a valid BST:
- The left subtree of a node contains only nodes with keys less than the node's key
- The right subtree of a node contains only nodes with keys greater than the node's key
- Both the left and right subtrees must also be binary search trees
Constraints:
- There can be duplicates. In this case, return false
- Return true if there's only one node in the tree
- Return true if the tree is empty
*/
// ---- Solution ----
const dfs = function (node, lower, upper) {
if (node.val <= lower || node.val >= upper) {
return false;
}
if (node.left) {
if (!dfs(node.left, lower, node.val)) {
return false;
}
}
if (node.right) {
if (!dfs(node.right, node.val, upper)) {
return false;
}
}
return true;
};
const isValidBST = function (root) {
if (!root) return true;
return dfs(root, -Infinity, Infinity);
};
// ---- Space and Time Complexity ----
/*
Time: O(n)
Space: O(n)
*/