
Problem
Solution
Submissions
Binary Tree is a Valid BST
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
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. - Both the left and right subtrees must also be binary search trees.
Example 1
- Input:
- Output: true
- Explanation:
- The binary tree has root value 2, left child with value 1, and right child with value 3.
- This forms a valid BST.
Example 2
- Input:
- Output: false
- Explanation:
- The node with value 4 has a left child with value 3, which is valid.
- However, it also has a right child with value 6, which is greater than the root value 5.
- This violates the BST property.
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
- Use recursion to check each subtree.
- Keep track of the valid range for each node.
- Traverse the tree in-order and check if values are in ascending order.
- Be careful about edge cases with duplicate values.