-
Notifications
You must be signed in to change notification settings - Fork 0
Validate Binary Search Tree
Roberto Fronteddu edited this page Aug 15, 2024
·
2 revisions
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
class Solution {
public boolean isValidBST (TreeNode root) {
if (root == null) {
return true;
}
return validBST (root, null, null);
}
boolean validBST (TreeNode node, Integer min, Integer max) {
if (node == null) {
return true;
}
// Check if the current node's value is within the valid range
if ((min != null && node.val <= min) || (max != null && node.val >= max)) {
return false;
}
// Left Subtree Constraint: When you go to the left child, you update the max value
// because all nodes in the left subtree must be less than the current node's value.
// Hence, you check if the left child respects this constraint.
// Right Subtree Constraint: When you go to the right child, you update the min value
// because all nodes in the right subtree must be greater than the current node's value.
// Hence, you check if the right child respects this constraint.
// Recursively validate the left and right subtrees with updated min and max values
return validBST(node.left, min, node.val) && validBST(node.right, node.val, max);
}
}