Validate Binary Search Tree - Problem
You're given the root of a binary tree and need to determine if it represents a valid Binary Search Tree (BST).
A valid BST must satisfy these strict rules:
- All nodes in the left subtree have values strictly less than the current node's value
- All nodes in the right subtree have values strictly greater than the current node's value
- Both left and right subtrees must also be valid BSTs
โ ๏ธ Important: The key word here is "strictly" - no duplicate values are allowed, and the BST property must hold for all descendants, not just immediate children!
For example, a tree where the root is 5, left child is 3, and the left child of 3 is 7 would be invalid because 7 > 5, violating the BST property even though 7 > 3.
Input & Output
example_1.py โ Valid BST
$
Input:
root = [5,3,8,1,4,null,9]
โบ
Output:
true
๐ก Note:
This forms a valid BST. Inorder traversal gives [1,3,4,5,8,9] which is in strictly ascending order. All left descendants < root < all right descendants for every node.
example_2.py โ Invalid BST
$
Input:
root = [5,3,8,1,6,null,9]
โบ
Output:
false
๐ก Note:
Node 6 is in the left subtree of root 5, but 6 > 5, violating the BST property. Even though 6 > 3 (its parent), it must also be < 5 (the root ancestor).
example_3.py โ Edge Case with Duplicates
$
Input:
root = [5,5,7]
โบ
Output:
false
๐ก Note:
BST requires strictly less/greater values. Having a duplicate value 5 in the left subtree violates the 'strictly less' requirement.
Visualization
Tap to expand
Understanding the Visualization
1
Start at Root
Begin validation journey at the family head
2
Visit Left Branch
Check all left descendants have smaller salaries
3
Process Current
Validate current person's salary is in correct order
4
Visit Right Branch
Check all right descendants have larger salaries
5
Maintain Order
Ensure the salary sequence keeps increasing
Key Takeaway
๐ฏ Key Insight: A valid BST's inorder traversal always produces strictly ascending values. Instead of checking ranges for each node, we can simply verify this ordering property during traversal - elegant and efficient!
Time & Space Complexity
Time Complexity
O(n)
Visit each node exactly once during inorder traversal
โ Linear Growth
Space Complexity
O(h)
Recursion stack depth equals tree height h (O(log n) for balanced, O(n) for skewed)
โ Linear Space
Constraints
- The number of nodes in the tree is in the range [0, 104]
- -231 โค Node.val โค 231 - 1
- Tree nodes contain unique values (but this needs to be validated!)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code