Problem Description
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.
Examples
Example 1: Input: root = [2,1,3] Output: true Example 2: Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4.
Python Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def isValidBST(root: Optional[TreeNode]) -> bool:
def validate(node: Optional[TreeNode], min_val: float, max_val: float) -> bool:
if not node:
return True
if node.val <= min_val or node.val >= max_val:
return False
return validate(node.left, min_val, node.val) and \
validate(node.right, node.val, max_val)
return validate(root, float('-inf'), float('inf'))
Java Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean validate(TreeNode node, long minVal, long maxVal) {
if (node == null) {
return true;
}
if (node.val <= minVal || node.val >= maxVal) {
return false;
}
return validate(node.left, minVal, node.val) &&
validate(node.right, node.val, maxVal);
}
}
C++ Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
bool validate(TreeNode* node, long minVal, long maxVal) {
if (!node) {
return true;
}
if (node->val <= minVal || node->val >= maxVal) {
return false;
}
return validate(node->left, minVal, node->val) &&
validate(node->right, node->val, maxVal);
}
public:
bool isValidBST(TreeNode* root) {
return validate(root, LONG_MIN, LONG_MAX);
}
};
JavaScript Solution
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function(root) {
const validate = (node, minVal, maxVal) => {
if (!node) {
return true;
}
if (node.val <= minVal || node.val >= maxVal) {
return false;
}
return validate(node.left, minVal, node.val) &&
validate(node.right, node.val, maxVal);
};
return validate(root, -Infinity, Infinity);
};
C# Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public bool IsValidBST(TreeNode root) {
return Validate(root, long.MinValue, long.MaxValue);
}
private bool Validate(TreeNode node, long minVal, long maxVal) {
if (node == null) {
return true;
}
if (node.val <= minVal || node.val >= maxVal) {
return false;
}
return Validate(node.left, minVal, node.val) &&
Validate(node.right, node.val, maxVal);
}
}
Complexity Analysis
- Time Complexity: O(n) where n is the number of nodes in the tree
- Space Complexity: O(h) where h is the height of the tree
Solution Explanation
This solution uses recursive validation with range checking:
- Key concept:
- Track valid ranges
- Recursive validation
- Handle edge cases
- Algorithm steps:
- Check node value
- Update valid ranges
- Validate subtrees
- Handle base cases
Key points:
- Range validation
- Handle integer limits
- Recursive approach
- Efficient traversal