11. Check for BST
The problem can be found at the following link: Question Link
Problem Description
Given the root of a binary tree, check whether it is a Binary Search Tree (BST) or not.
Definition of BST:
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.
Note: BSTs cannot contain duplicate nodes.
Examples
Example 1:
Input:
root = [2, 1, 3, N, N, N, 5]
Output:
Explanation:
The left subtree of every node contains smaller keys and right subtree of every node contains greater keys. Hence, it is a BST.
Example 2:
Input:
root = [2, N, 7, N, 6, N, 9]
Output:
Explanation:
Since the node to the right of node with key
7has lesser key value, Hence, it is not a BST.
Example 3:
Input:
root = [10, 5, 20, N, N, 9, 25]
Output:
Explanation:
The node with key
9present in the right subtree has lesser key value than root node. Hence, it is not a BST.
Constraints:
1 ≤ Number of nodes ≤ $10^5$
1 ≤ node->data ≤ $10^9$
My Approach
✅ Min–Max Recursion (Top-Down Approach)
Base Case:
If the current node is
NULL, returntrue(an empty tree is a valid BST).
Check Current Node:
The current node’s value should be greater than the
minvalue and less than themaxvalue.
Recursive Calls:
Recursively check the left subtree with the updated range
[min, node->data].Recursively check the right subtree with the updated range
[node->data, max].
Return Result:
The tree is a BST only if both left and right subtrees are BSTs.
Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N)We visit each node exactly once, performing constant-time operations at each step.Expected Auxiliary Space Complexity:
O(H)Due to the recursion stack, whereHis the height of the tree. In the worst case (skewed tree),H = N. In the best case (balanced tree),H = log N.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated