Trim a binary search tree solution explained
To trim a binary search tree to a range [low, high], recurse with one rule per node: if its value is below low, the node and its whole left subtree go, so return the trimmed right subtree; if above high, return the trimmed left subtree; otherwise keep the node and trim both children. This keeps every surviving node's ancestors in the same order, runs in O(n) time and uses O(h) recursion, and an iterative version does it with O(1) extra space.
By Evin JohnPublished 7 min read
The problem in plain words
You get the root of a binary search tree and two bounds, low and high. Remove every node whose value falls outside the range, and return the root of what remains. The result must still be a valid BST and must keep the remaining nodes' relationships: if one kept node was a descendant of another before, it still is. The root may change, and the result may be empty.
Before: After:
10 10
/ \ / \
4 15 7 12
/ \ / \ / \
2 7 12 20 6 13
/ \
6 134 is too small, and so is everything on its left (2), but its right subtree (7 and 6) is in range and takes 4's place under 10. 15 is too big, and so is everything on its right (20), so its left subtree (12 and 13) takes its place.
Why it is asked
This is a test of whether you use the BST property rather than treating the tree as a generic binary tree. Candidates who delete nodes one by one, with all the usual successor juggling, write a page of fragile code. Candidates who see that an out-of-range node discards an entire side write five lines. It also checks the idiom of a recursive function that returns the new subtree root, which appears in insertion, deletion and many tree-rebuilding problems.
A slower but obviously correct route
Walk the tree in preorder and collect the values that are in range. Then insert them, in that order, into an empty BST. Preorder lists every parent before its descendants, so each kept node is inserted before any kept node below it, and the BST insertion rule then places descendants on the same side they were on before. The result is the same tree the direct trim produces. Each insertion costs up to O(h), so this is O(n·h), and it allocates a new tree. It makes a good test oracle.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def trim_by_rebuilding(root, low, high):
kept = []
def preorder(node):
if node:
if low <= node.val <= high:
kept.append(node.val)
preorder(node.left)
preorder(node.right)
def insert(node, val):
if node is None:
return TreeNode(val)
if val < node.val:
node.left = insert(node.left, val)
else:
node.right = insert(node.right, val)
return node
preorder(root)
new_root = None
for val in kept: # parents arrive before their descendants
new_root = insert(new_root, val)
return new_rootRecursive trim using the BST property
Look at one node. If its value is below low, every value in its left subtree is smaller still, so all of it goes. Only its right subtree can contain survivors, so the answer for this position is the trimmed right subtree. Symmetrically, a value above high means the answer is the trimmed left subtree. A value inside the range stays, and its two children are replaced by their own trimmed versions. Each node is visited at most once.
def trim_bst(node, low, high):
if node is None:
return None
if node.val < low: # node and its whole left side are too small
return trim_bst(node.right, low, high)
if node.val > high: # node and its whole right side are too big
return trim_bst(node.left, low, high)
node.left = trim_bst(node.left, low, high)
node.right = trim_bst(node.right, low, high)
return nodefunction trimBST(node, low, high) {
if (!node) return null;
if (node.val < low) return trimBST(node.right, low, high);
if (node.val > high) return trimBST(node.left, low, high);
node.left = trimBST(node.left, low, high);
node.right = trimBST(node.right, low, high);
return node;
}Trace on the example. 10 is in range, so trim its children. Left: 4 is below 5, so return the trim of 4's right child, 7. 7 is in range; its left child 6 is in range, its right is empty. So 10's left becomes 7. Right: 15 is above 13, so return the trim of 15's left child, 12. 12 is in range; its right child 13 is in range. So 10's right becomes 12.
Follow-up: iterative, O(1) extra space
First move down from the root until you land on a node inside the range; that is the new root. Then fix the left spine: walking down left children, whenever a left child is below low, replace it with its own right child and check again. Nothing in this new root's left subtree can exceed high, because it is all smaller than the root. Fix the right spine the same way for values above high.
def trim_bst_iterative(root, low, high):
while root and not (low <= root.val <= high): # find the new root
root = root.right if root.val < low else root.left
if root is None:
return None
node = root
while node: # left spine: only values below low can appear
while node.left and node.left.val < low:
node.left = node.left.right
node = node.left
node = root
while node: # right spine: only values above high can appear
while node.right and node.right.val > high:
node.right = node.right.left
node = node.right
return rootComplexity
| Approach | Time | Extra space |
|---|---|---|
| Rebuild by reinsertion | O(n·h), O(n²) on a chain | O(n) new nodes |
| Recursive trim | O(n) | O(h) recursion |
| Iterative spine fixing | O(n) | O(1) |
Edge cases to test
- A range that contains every value: the tree comes back unchanged.
- A range below or above every value: the result is empty.
- A root outside the range, so the returned root is a different node.
- low equal to high, keeping at most one node.
- Bounds that match existing values exactly; both ends are inclusive.
Common mistakes
- Returning
Nonefor an out-of-range node, which throws away valid nodes in its other subtree. - Recursing into the wrong side: a value below low must continue into the right subtree, not the left.
- Trimming the children but not assigning the results back to
node.leftandnode.right. - Forgetting that the root can change and returning the original root.
- Using strict comparisons and dropping nodes equal to low or high.
How to explain it out loud
Fictional example
- Candidate
- Because this is a BST, if a node is below low then its whole left subtree is below low too. So the only part that can survive is its right subtree, and I return the trimmed right subtree in its place.
- Candidate
- The mirror case handles values above high. A node in range stays, and I replace its children with their trimmed versions.
- Candidate
- Every node is looked at once, so O(n) time, plus the recursion depth. If you want constant space, I can find the new root and then fix the two spines with a loop.
Related problems
Another BST repair that relies on sorted order is Recover Binary Search Tree, where two values have swapped places. The return-the-new-subtree idiom also shows up when you rebuild a tree in Construct Binary Tree from Inorder and Postorder. For a bottom-up decision problem on a general tree, see Binary Tree Cameras, and the coding problems hub for everything else.
Practicing with Natively
Trimming is easy to get almost right, which is why tracing matters. In practice, Natively can read a BST drawing and the range from a screenshot on Mac or Windows, step through which side survives at each node, and compare your code with the iterative variant. The transcript of your mock interview lets you hear whether you stated the BST argument before you started coding.
Questions people ask
How do you trim a binary search tree?
Recurse with three cases: a node below low is replaced by its trimmed right subtree, a node above high by its trimmed left subtree, and a node in range keeps its place with both children trimmed.
Why can a whole subtree be discarded when trimming a BST?
In a BST every value in a node's left subtree is smaller than the node. If the node is already below low, its entire left subtree is too, and the mirror holds above high.
What is the time complexity of trimming a BST?
O(n) time, since each node is visited at most once, with O(h) recursion space, or O(1) extra space with the iterative version.
Can the root change when trimming a BST?
Yes. If the root is outside the range, the new root is the first in-range node found by moving right or left from it, and the result can be empty.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
