
Problem
Solution
Submissions
Binary Search Tree
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a Java program to determine if a given binary tree is a valid Binary Search Tree (BST). A valid BST is defined as follows:
- All nodes in the left subtree of a node have values less than the node's value.
- All nodes in the right subtree of a node have values greater than the node's value.
- Both the left and right subtrees must also be valid binary search trees.
Example 1
- Input:
- Tree:
- Tree:
- Output: true
- Explanation:
- Root value is 2.
- Left child value is 1, which is less than 2. Valid.
- Right child value is 3, which is greater than 2. Valid.
- Both subtrees are also valid BSTs.
- Therefore, the entire tree is a valid BST.
Example 2
- Input:
- Tree:
- Tree:
- Output: false
- Explanation:
- Root value is 5.
- Left child value is 1, which is less than 5. Valid.
- Right child value is 4, which is less than 5. Invalid.
- Check the subtree with root 4.
- Left child of 4 is 3, which is less than 4. Valid.
- Right child of 4 is 6, which is greater than 4 but also greater than the root 5. Invalid.
- Therefore, the tree 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 in the tree
- Space Complexity: O(h), where h is the height of the tree (due to recursion stack)
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 approach (left-root-right)
- For a valid BST, in-order traversal should produce sorted values
- Alternatively, check each node against valid value ranges
- Use recursion to validate left and right subtrees
- Handle edge cases such as empty trees or trees with duplicate values