FastPrepTrim a Binary Search Tree

Trim a Binary Search Tree

Bloomberg LP logoBloomberg LP● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

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

Keep the relative structure of retained nodes unchanged. Return the trimmed root; 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 range 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 too large. Valid descendants from the left branch remain 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

  • The tree contains between 0 and 100000 nodes.
  • -1000000000 <= Node.val, low, high <= 1000000000.
  • low <= high.
  • All node values are distinct, and the input is a valid binary search tree.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public TreeNode trimBST(TreeNode root, int low, int high) {
    // Write your code here.
}
root[1,0,2]
low1
high2
expected[1,null,2]
Checking account…