Trees: count values in range
Trees: count values in range
You have a binary search tree and a range [lo, hi]. Count how many node
values v satisfy lo <= v <= hi.
You could visit every node — but a BST lets you prune. If a node's value
is below lo, every value in its left subtree is also too small, so skip
the left entirely. If it's above hi, skip the right. That's the payoff
for keeping the tree sorted.
Counting values in [3, 7] on this BST — watch the pruning save work:
5 5 is in [3, 7] ✓
/ \
3 8 8 > 7 → skip 8's RIGHT subtree entirely
/ \ /
2 4 7 2 < 3 → skip 2's children; 4 ✓ 7 ✓
In range: 3, 4, 5, 7 → count = 4. Trees here are built by
build_bst(values): each int is inserted in order, < node going left and
>= going right.
Your task
Write range_count(root, lo, hi) returning the number of node values v with
lo <= v <= hi. Use the BST property to avoid exploring subtrees that can't
contain a match.
range_count(build_bst([5, 3, 8, 2, 4, 7]), 3, 7) # 4 (3, 4, 5, 7)
range_count(build_bst([5, 3, 8, 2, 4, 7]), 0, 100) # 6 (all of them)
range_count(build_bst([]), 0, 9) # 0
Hint: count this node if it's in range; recurse left only when
root.val > lo, and right only when root.val < hi.
Tests
- inner range
- covers all
- empty tree
- upper only (hidden)
- none match (hidden)
- single point (hidden)
Stuck? Ask for a spark
$ Console output will appear here.