
Problem
Solution
Submissions
Validate Binary Search Tree
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a Python function to validate if a given binary tree 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.
Algorithm for is_valid_bst(root)
- Use a recursive approach to validate each node in the tree.
- For each node, track the valid range of values (lower and upper bounds).
- Validate that the current node's value falls within the valid range.
- Update the valid range when traversing to left and right subtrees.
- Return true if all nodes satisfy the BST property, false otherwise.
Example 1
- Input:
2
/ \
1 3 - Output: true
- Explanation:
- The tree has the following structure:
- - Root node with value 2
- - Left child with value 1 (less than 2)
- - Right child with value 3 (greater than 2)
- All BST properties are satisfied.
Example 2
- Input:
5
/ \
1 4
/ \
3 6 - Output: false
- Explanation:
- The tree has the following structure:
- - Root node with value 5
- - Left child with value 1 (less than 5)
- - Right child with value 4 (less than 5, which violates BST property)
- - Left child of 4 is 3 (less than 4)
- - Right child of 4 is 6 (greater than 4)
- The value 4 is not greater than 5, so this is not a valid BST.
Constraints
- The number of nodes in the tree is in the range [1, 10^4]
- -2^31 <= Node.val <= 2^31 - 1
- Time Complexity: O(n) where n is the number of nodes
- Space Complexity: O(h) where h is the height of the tree
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Consider using an in-order traversal to check if the values are in ascending order
- Alternatively, use a recursive approach with upper and lower bounds for each node
- Remember that each node must be greater than all nodes in its left subtree and less than all nodes in its right subtree
- Track the valid range for each node as you traverse down the tree
- Be careful about handling duplicate values according to the problem's definition