
Problem
Solution
Submissions
Validate Binary Search Tree
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to determine 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, and both the left and right subtrees must also be binary search trees.
Example 1
- Input: Tree structure [2,1,3]
- Output: true
- Explanation:
- Root node is 2, left child is 1, right child is 3.
- Left subtree contains only values less than 2 (which is 1).
- Right subtree contains only values greater than 2 (which is 3).
- Therefore, this is a valid BST.
- Root node is 2, left child is 1, right child is 3.
Example 2
- Input: Tree structure [5,1,4,null,null,3,6]
- Output: false
- Explanation:
- Root node is 5, left child is 1, right child is 4.
- The right subtree has root 4, which is less than 5 (valid so far).
- Node 4 has left child 3 and right child 6.
- Node 3 is in the right subtree of root 5, but 3 < 5, violating BST property.
- Therefore, this is not a valid BST.
- Root node is 5, left child is 1, right child is 4.
Constraints
- The number of nodes in the tree is in the range [1, 10^4]
- -2^31 ≤ Node.val ≤ 2^31 - 1
- You must validate the entire tree structure
- Time Complexity: O(n)
- 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
- Use in-order traversal to check if the values are in ascending order
- Alternatively, use a recursive approach with min and max bounds
- For each node, check if its value is within the valid range
- Update the range for left and right subtrees accordingly
- The left subtree should have values less than current node
- The right subtree should have values greater than current node