Count BST ndoes that lie in a given range
Pattern: Search, insert and delete
Count values in [l, h]. At a node below l, the whole left subtree is too small: only search the right. Above h, only search the left. Otherwise count the node and search both sides.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Return how many values of the BST lie in the range [l, h], both ends included. The example gives 3. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- If a node is below l, can anything in its left subtree be in range?
- And if it is above h?
- When must you look at both sides?
Hints
Brute force, and why it fails
Visit every node: O(n).
The key insight
The BST order lets you skip whole subtrees that are entirely outside the range.
Dry run
| count | 1 |
|---|
BST [10, 5, 50, 1, null, 40, 100], range [5, 45]. 10 is inside: count it and look both ways.
The plan
count(n): if null: 0
if n.val < l: count(n.right)
elif n.val > h: count(n.left)
else: 1 + count(n.left) + count(n.right)
Complexity
- Time
O(h + k)- Space
O(h)
k is the number of values in range.
Edge cases
- An empty range.
- Every value in range.
- l equal to h.
I've built my logic, show the code
Java
class Solution {
public int getCount(TreeNode root, int l, int h) {
if (root == null) return 0;
if (root.val < l) return getCount(root.right, l, h); // everything on the left is too small
if (root.val > h) return getCount(root.left, l, h); // everything on the right is too big
return 1 + getCount(root.left, l, h) + getCount(root.right, l, h);
}
}C++
class Solution {
public:
int getCount(TreeNode* root, int l, int h) {
if (root == NULL) return 0;
if (root->val < l) return getCount(root->right, l, h); // everything on the left is too small
if (root->val > h) return getCount(root->left, l, h); // everything on the right is too big
return 1 + getCount(root->left, l, h) + getCount(root->right, l, h);
}
};Python
class Solution:
def getCount(self, root, l: int, h: int) -> int:
if root is None:
return 0
if root.val < l:
return self.getCount(root.right, l, h) # everything on the left is too small
if root.val > h:
return self.getCount(root.left, l, h) # everything on the right is too big
return 1 + self.getCount(root.left, l, h) + self.getCount(root.right, l, h)Common mistakes
- Searching both sides even when one is ruled out.
- Excluding the ends of the range.