Problem 419
Trim a Binary Search Tree
Medium · 20 pts · Tree, Binary Search Tree, Recursion
Problem
Trim a binary search tree so that all its values lie in the range [L, R], removing every node outside the range. The remaining nodes keep their relative structure: if a node is kept, any kept descendant stays a descendant. When a node is too small, it is replaced by its trimmed right subtree; when it is too large, by its trimmed left subtree. Print the resulting tree in level order, or EMPTY if no node is left.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode. The third line contains L and R.
Output
Print the trimmed tree in level order with 'null' for missing children and no trailing nulls, or EMPTY.
Constraints
1 <= number of nodes <= 10000; values are distinct; 0 <= L <= R <= 10000
Example input
8 3 0 4 null 2 null null 1 1 3
Example output
3 2 null 1
Explanation
Trimming 3 / 0 4 / _ 2 / 1 to the range [1, 3] removes 0 and 4. The node 2 takes 0's place under 3, and 1 stays below 2, giving 3 2 null 1.