-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisValidBST.js
More file actions
executable file
·68 lines (49 loc) · 1.91 KB
/
isValidBST.js
File metadata and controls
executable file
·68 lines (49 loc) · 1.91 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Validate Binary Search Tree
// what is valid binary search tree?
// A valid binary search tree (BST) is a binary tree in which for every node, all values in its left subtree are less than the node's value, and all values in its right subtree are greater than the node's value. This property must hold true for all nodes in the tree.
// Mental model:
// “A binary search tree is like a sorted library where each book (node) has all the books with smaller titles (values) to its left and all the books with larger titles to its right.”
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function isValidBST(root) {
function validate(node, low = -Infinity, high = Infinity) {
if (!node) return true;
if (node.value <= low || node.value >= high) {
return false;
}
return validate(node.left, low, node.value) &&
validate(node.right, node.value, high);
}
return validate(root);
}
// Example usage:
// Creating a sample valid BST:
// 2
// / \
// 1 3
let root = new TreeNode(2);
root.left = new TreeNode(1);
root.right = new TreeNode(3);
console.log(isValidBST(root)); // Output: true
// Creating a sample invalid BST:
// 5
// / \
// 1 4
// / \
// 3 6
let root2 = new TreeNode(5);
root2.left = new TreeNode(1);
root2.right = new TreeNode(4);
root2.right.left = new TreeNode(3);
root2.right.right = new TreeNode(6);
console.log(isValidBST(root2)); // Output: false
// time complexity: O(n) where n is the number of nodes in the tree
// space complexity: O(h) where h is the height of the tree (due to recursion stack)
// edge cases
console.log(isValidBST(null)); // Output: true (an empty tree is a valid BST)
console.log(isValidBST(new TreeNode(10))); // Output: true (a single node tree is a valid BST)