-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path98-validate-binary-search-tree.ts
More file actions
32 lines (26 loc) · 989 Bytes
/
Copy path98-validate-binary-search-tree.ts
File metadata and controls
32 lines (26 loc) · 989 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
/**
* Solution explanation:
* Helper function with minimum and maximum to bound the values node in
* this subtree can be
*/
class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
}
}
function isValidBST(root: TreeNode | null): boolean {
function helper(node: TreeNode | null, min: number, max: number): boolean {
if (node === null) return true;
if (node.val <= min || node.val >= max) return false;
// this is max of left subtree, and min of right subtree
const leftValid = helper(node.left, min, node.val);
const rightValid = helper(node.right, node.val, max);
return leftValid && rightValid;
}
return helper(root, -Infinity, Infinity);
};