Skip to the code
cf.
+25 XP

#341 Trim the Catalog to a Price Band

medium

A store's "budget picks" page only shows products priced from low to high. Prices are stored in a binary search tree with unique values.

Write trimToBand(root, low, high) that removes every node outside low..high and returns the new root. Nodes that remain must keep their relative positions: if a kept node was below another kept node, it stays below it. This makes the result unique.

Example 1

Input: root = [10,5,15,3,7,null,18], low = 5, high = 15
Output: [10,5,15,null,7]

3 and 18 are outside the band and are removed.

Example 2

Input: root = [10,5,15,3,7,null,18], low = 6, high = 8
Output: [7]

Only 7 is in the band, so it becomes the root.

Constraints

  • 0 <= number of prices <= 10000
  • 0 <= low <= high <= 10^4

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).