FastPrepTrim a Binary Search Tree to a Range
Problems/Trim a Binary Search Tree to a Range

Trim a Binary Search Tree to a Range

Google logoGoogle● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The report encodes references to LeetCode 1325, 814, and 669 and asks about a node becoming the new root plus removing a condition. The root-changing cue most directly identifies the range-trimming contract of 669; FastPrep uses that conventional statement and records the other two pruning references as alternatives. Match is about 82%.

Given the root of a binary search tree and an inclusive range [low, high], remove every node whose value lies outside the range.

The relative structure of retained nodes must remain unchanged. Return the root of the trimmed tree; a retained descendant may become the new root.

Function

trimBST(root: TreeNode, low: int, high: int) → TreeNode

Examples

Example 1

root = [1,0,2]low = 1high = 2return = [1,null,2]

Node 0 is below the interval and is removed.

Example 2

root = [3,0,4,null,2,null,null,1]low = 1high = 3return = [3,2,null,1]

The branch rooted at 4 is above the interval. The valid descendants from the left branch remain attached in BST order.

Example 3

root = [0,null,1]low = 1high = 2return = [1]

The original root is too small, so its retained right child becomes the new root.

Constraints

  • 0 <= number of nodes <= 10^5.
  • -10^9 <= node.val, low, high <= 10^9.
  • low <= high, and all node values are distinct.
  • The input is a valid binary search tree.

More Google problems

  • Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
  • Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
  • 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
All Google interview questionsSee Google hiring insights
Saved
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        // Write your solution here.
    }
}
Checking account…