Skip to content

Commit f169fa3

Browse files
committed
solve: Week 02 validate binary search tree
1 parent 9450188 commit f169fa3

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
// Helper function to check if a tree is a valid binary search tree
14+
function isValidTree(node: TreeNode | null, min: number | null, max: number | null): boolean {
15+
// If the node is null, the tree is valid
16+
if (node === null) return true;
17+
18+
// If the node's value is less than the minimum or greater than the maximum, the tree is not valid
19+
if ((min !== null && node.val <= min) || (max !== null && node.val >= max)) {
20+
return false;
21+
}
22+
23+
// Recursively check the left and right subtrees
24+
return isValidTree(node.left, min, node.val) && isValidTree(node.right, node.val, max);
25+
}
26+
27+
// Check if the tree is a valid binary search tree
28+
return isValidTree(root, null, null);
29+
}

0 commit comments

Comments
 (0)