Skip to content

Commit 6154fb4

Browse files
committed
2week: 98. Validate Binary Search Tree
1 parent abd2551 commit 6154fb4

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class TreeNode {
2+
val: number;
3+
left: TreeNode | null;
4+
right: TreeNode | null;
5+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
this.val = val === undefined ? 0 : val;
7+
this.left = left === undefined ? null : left;
8+
this.right = right === undefined ? null : right;
9+
}
10+
}
11+
12+
function isValidBST(root: TreeNode | null): boolean {
13+
function valid(node, min, max) {
14+
if (!node) return true;
15+
16+
if (node.val <= min || node.val >= max) return false;
17+
18+
return valid(node.left, min, node.val) && valid(node.right, node.val, max);
19+
}
20+
21+
return valid(root, -Infinity, Infinity);
22+
}

0 commit comments

Comments
 (0)