← Practice
📖 Trees and binary search treesLearning path
Browsing as guest·Sign in or create a free account to save progress and use tutor tools.
Lesson·difficulty 3/5·~16 min

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:

text
        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.

python
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

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.