-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.js
More file actions
33 lines (26 loc) · 776 Bytes
/
BST.js
File metadata and controls
33 lines (26 loc) · 776 Bytes
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
class TreeNode {
constructor(val) {
this.val = val
this.right = null
this.left = null
}
}
const isValidBST = (root) => {
const helper = (node, lower, upper) => {
if (!node) return true
const { val } = node
if (val <= lower || val >= upper) return false
if (!helper(node.right, val, upper)) return false
if (!helper(node.left, lower, val)) return false
return true
}
return helper(root, -Infinity, Infinity)
}
const node = new TreeNode(10)
node.left = new TreeNode(5)
node.right = new TreeNode(15)
/// True
console.log(isValidBST(node))
node.right.left = new TreeNode(9)
/// False
console.log(isValidBST(node))