forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0098-validate-binary-search-tree.js
72 lines (58 loc) · 1.64 KB
/
0098-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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* https://leetcode.com/problems/validate-binary-search-tree/
* Time O(N) | Space O(H)
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function(root, min = -Infinity, max = Infinity) {
const isBaseCase = root === null;
if (isBaseCase) return true;
const isInvalid = (root.val <= min) || (max <= root.val);
if (isInvalid) return false;
return dfs(root, min, max);
};
const dfs = (root, min, max) => {
const left = isValidBST(root.left, min, root.val);
const right = isValidBST(root.right, root.val, max);
return left && right;
}
// TODO
/**
* https://leetcode.com/problems/validate-binary-search-tree/
* Time O(N) | Space O(H)
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function(root, prev = [ null ]) {
const isBaseCase = root === null;
if (isBaseCase) return true;
if (!isValidBST(root.left, prev)) return false;
const isInvalid = (prev[0] !== null) && (root.val <= prev[0]);
if (isInvalid) return false;
prev[0] = root.val;
return isValidBST(root.right, prev);
}
/**
* https://leetcode.com/problems/validate-binary-search-tree/
* Time O(N) | Space O(H)
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function(root, stack = []) {
let prev = null;
while (stack.length || root) {
moveLeft(stack, root);
root = stack.pop();
const isInvalid = prev && (root.val <= prev.val);
if (isInvalid) return false;
prev = root;
root = root.right;
}
return true;
}
const moveLeft = (stack, root) => {
while (root) {
stack.push(root);
root = root.left;
}
}