← OYO questions

Remove BST Keys Outside Range

Filed under OYO · Also reported at Samsung

Free read 1 of 3

If node value < min, return the result of trimming the right subtree. If node value > max, return the result of trimming the left subtree.

The question

Given the root of a Binary Search Tree (BST) and the lowest and highest boundaries as min and max, trim the tree so that all its nodes have values in [min, max].

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • 0 <= Node.val <= 10^4

Examples

Input
root = [3,0,4,null,2,null,null,1], min = 1, max = 3
Output
[3,2,null,1]
Why
Nodes with values 0 and 4 are removed.

Approach

  1. If node value < min, return the result of trimming the right subtree. If node value > max, return the result of trimming the left subtree.

Tips

  • What they are testing: Test cases where the root itself needs to be deleted.
  • Common mistake: Failing to reassign the result of the recursive call to the parent's left or right pointer.

Related OYO questions

Collected from public candidate posts and coding forums. Updated Nov 2026.