We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy trees problem, graded against 6 test cases (3 of them hidden).
Recursive traversal of binary trees and BSTs - depth, validation, and path problems.
Reach for it when you see: A TreeNode input, or anything about depth, ancestry, or in-order ordering.
More Treesproblems →Summing every node and filtering by range gives the right answer in O(n) and misses what is being tested. The BST invariant - everything left is smaller, everything right is larger - means whole subtrees can be ruled out without looking at them.
At each node there are three cases. If the value is less than `low`, every value in the left subtree is smaller still and cannot qualify, so recurse right only. If it exceeds `high`, recurse left only. Otherwise the value counts, and both sides may contain more.
On a balanced tree with a narrow range this turns O(n) into something closer to O(log n + k) for k results, since the traversal descends to the range and covers only the nodes inside it plus the boundary path.
The same pruning idea drives BST search, `floor`/`ceiling` queries, and validating a BST with min/max bounds. Recognizing when an invariant lets you *not* look at data is the transferable skill here.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.