Trim a Binary Search Tree

Medium Trees & BST BST Basics

Trim a Binary Search Tree is a medium trees & bst problem solved with the bst basics pattern. The best approach, optimal (iterative, o(1) extra space), runs in O(n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (trim every subtree, then decide) up.

Problem

You are given the root of a binary search tree and two bounds low and high. Remove every node whose value lies outside the range [low, high], and return the root of what is left.

The nodes that remain must keep their relative structure: if a surviving node was somewhere below another surviving node, it must still be below it, on the same side, in the result. In other words, you only cut nodes out and reconnect the pieces; you never reorder anything. The result is still a valid binary search tree, and it is unique.

The root of the result may be a different node than the original root. If no value lies in the range, return an empty tree.

Examples

Example 1

Input
root = [1, 0, 2], low = 1, high = 2
Output
[1, null, 2]
Why
0 is below the range, so it goes. 1 and 2 stay, and 2 is still the right child of 1.

Example 2

Input
root = [6, 2, 8, 1, 4, 7, 9, null, null, 3, 5], low = 3, high = 7
Output
[6, 4, 7, 3, 5]
Why
2 is too small, and so is its left child 1, but its right subtree 4, 3, 5 is inside the range: it moves up and takes 2's place as the left child of 6. 8 is too big, and so is 9, but its left child 7 fits and becomes the right child of 6.

Example 3

Input
root = [5, 3, 8, 1, 4], low = 4, high = 4
Output
[4]
Why
Only 4 is inside the range. It was a leaf two levels down, and it becomes the new root.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • 0 <= Node.val <= 10^4
  • All node values are distinct.
  • root is a valid binary search tree.
  • 0 <= low <= high <= 10^4

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 22 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (trim every subtree, then decide)O(n)O(h)
Recursive pruning with the BST orderO(n)O(h)
Optimal (iterative, O(1) extra space)O(n)O(1)

1Brute force (trim every subtree, then decide)

TimeO(n)Every one of the n nodes is visited exactly once, including whole subtrees that end up removed.
SpaceO(h)The recursion goes as deep as the height h of the tree.

Treat it as a plain post-order problem. Trim the left and right subtrees first, without looking at the current node, then decide about the node itself. If it is inside the range it keeps its two trimmed children. If it is below low, everything in its left subtree is smaller still, so the trimmed left is empty and the trimmed right is the answer for this spot; above high is the mirror case. Correct, but it always walks every node, even subtrees that the BST order already tells us are entirely out of range.

  1. If root is null, return null.
  2. Trim root.left and root.right recursively into left and right.
  3. If root.val < low, return right; if root.val > high, return left.
  4. Otherwise attach left and right to root and return root.
class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) return null;
        TreeNode left = trimBST(root.left, low, high);
        TreeNode right = trimBST(root.right, low, high);
        if (root.val < low) return right;
        if (root.val > high) return left;
        root.left = left;
        root.right = right;
        return root;
    }
}

2Recursive pruning with the BST order

TimeO(n)Each node is visited at most once, and subtrees known to be out of range are skipped entirely.
SpaceO(h)The recursion follows one root-to-node path at a time: O(h), up to O(n) for a chain.

Decide about the node first and use the BST order to skip work. If the node is below low, then it and its entire left subtree are out, so throw that whole part away without visiting it and return the trimmed right subtree in its place. If it is above high, throw away it and its right subtree and return the trimmed left subtree. Otherwise the node stays, and we trim its two children and reattach them. Nodes that survive keep their relative order, because every surviving node is either kept in place or moved up into the spot of a removed ancestor, which keeps it on the same side of everything above.

  1. If root is null, return null.
  2. If root.val < low, return trimBST(root.right, low, high).
  3. If root.val > high, return trimBST(root.left, low, high).
  4. Otherwise set root.left and root.right to their trimmed versions and return root.
class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) return null;
        if (root.val < low) return trimBST(root.right, low, high);
        if (root.val > high) return trimBST(root.left, low, high);
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }
}

3Optimal (iterative, O(1) extra space)

TimeO(n)Each pointer step moves down the tree, and every node is passed at most once over the three walks.
SpaceO(1)Only a couple of node references; no recursion and no stack.

Do the same pruning with loops. First fix the root: while it is out of range, step right if it is too small and left if it is too big. Now the root is in range. Every node on its left side is smaller than the root, so it can only break the low bound. Walk down the left side: whenever the current node's left child is below low, replace that child by the child's own right subtree (the part that might still be large enough), and repeat until the left child fits; then move to it. The right side is the mirror image: only high can be broken, and a too-big right child is replaced by its left subtree. Each pointer is fixed in place, so no stack is needed.

  1. While root is not null and out of range, set root = root.right if root.val < low, else root = root.left. If root is now null, return null.
  2. Left side: cur = root; while cur is not null, replace cur.left by cur.left.right as long as cur.left.val < low, then cur = cur.left.
  3. Right side: cur = root; while cur is not null, replace cur.right by cur.right.left as long as cur.right.val > high, then cur = cur.right.
  4. Return root.
class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        while (root != null && (root.val < low || root.val > high)) {
            root = root.val < low ? root.right : root.left;
        }
        if (root == null) return null;
        TreeNode cur = root;
        while (cur != null) {
            while (cur.left != null && cur.left.val < low) cur.left = cur.left.right;
            cur = cur.left;
        }
        cur = root;
        while (cur != null) {
            while (cur.right != null && cur.right.val > high) cur.right = cur.right.left;
            cur = cur.right;
        }
        return root;
    }
}

Edge cases to test

  • No value lies in the range: the answer is the empty tree
  • Every value lies in the range: the tree comes back unchanged
  • The root itself is outside the range, so the new root is some node further down
  • low == high: at most one node survives
  • A long chain (every node has only a right child, or only a left child), which makes the recursion as deep as the tree
  • A removed node whose child subtree is partly inside the range: only the inside part is reattached

Hints

Hint 1

If a node's value is below low, what do you know about everything in its left subtree?

Hint 2

Such a node and its whole left subtree disappear, and the answer for that spot is simply the trimmed right subtree. The case above high is the mirror image.

Hint 3

If the node is inside the range, it stays: trim its left and right subtrees and hang the results back on it.

Hint 4

For O(1) extra space: first walk down until the root is in range. Then on the left side only low can be violated, and on the right side only high, so fix each side with one downward walk.

FAQ

What is the best time complexity for Trim a Binary Search Tree?

Optimal (iterative, O(1) extra space) runs in O(n) time and O(1) extra space. Each pointer step moves down the tree, and every node is passed at most once over the three walks.

Which pattern does Trim a Binary Search Tree use?

It is a trees & bst problem that uses the bst basics pattern. Other problems with the same pattern: Search in a Binary Search Tree, Minimum element in BST, Insert into a Binary Search Tree.

Is there a brute force solution for Trim a Binary Search Tree?

Yes. Brute force (trim every subtree, then decide) takes O(n) time and O(h) space. Treat it as a plain post-order problem.

Which edge cases should I test for Trim a Binary Search Tree?

No value lies in the range: the answer is the empty tree; Every value lies in the range: the tree comes back unchanged; The root itself is outside the range, so the new root is some node further down; low == high: at most one node survives; A long chain (every node has only a right child, or only a left child), which makes the recursion as deep as the tree; A removed node whose child subtree is partly inside the range: only the inside part is reattached.