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
- The number of nodes in the tree is in the range
[1, 10^4]. 0 <= Node.val <= 10^4- The value of each node in the tree is unique.
rootis guaranteed to be a valid binary search tree.0 <= low <= high <= 10^4
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
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Tree / Recursion problems
- Balanced Binary TreeEASY
- Binary Tree CamerasHARD
- Binary Tree Inorder TraversalEASY
- Binary Tree Maximum Path SumHARD
- Binary Tree PathsEASY
- Binary Tree Postorder TraversalEASY
- Binary Tree Preorder TraversalEASY
- House Robber IIIMEDIUM
- Construct Binary Tree from Inorder and Postorder TraversalMEDIUM
- Construct Binary Tree from Preorder and Inorder TraversalMEDIUM
- Convert BST to Greater TreeMEDIUM
- Count Complete Tree NodesEASY