AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Trim a Binary Search Tree

The key idea

Use the BST ordering. If a node's value is below low, its entire left subtree is also below low, so discard the node AND its left side and keep only the trimmed right child. Symmetrically, if a node is above high, keep only the trimmed left child. The pruned child is returned up and rewired into the parent.

Problem

Given the root of a binary search tree and two integers low and high, trim the tree so that all its elements lie in the range [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (that is, any node's descendant should remain a descendant). It can be proven that there is a unique answer.

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

Constraints

Examples

Input: root = [1,0,2], low = 1, high = 2 Output: [1,null,2]
Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3 Output: [3,2,null,1]

Complexity

Time: O(n) Space: O(h)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems