Python 0669.py
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:
return None
if root.val < low:
return self.trimBST(root.right, low, high)
if root.val > high:
return self.trimBST(root.left, low, high)
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
Difficulty
and has an acceptance rate of about 66% (400k+ submissions).
Typical patterns to solve this problem:
- Binary Search Tree
- Binary Tree
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a method trimBST that receives the root of a binary search tree (BST) together with lower and upper bounds (low and high). Its purpose is to return a new root that represents the original tree with all nodes whose values fall outside the inclusive interval [low, high] removed. The algorithm leverages the ordering property of BSTs to avoid unnecessary traversal, recursively rebuilding the tree only where needed.
Key Steps
Step 1 - Handling an empty subtree
if not root:
return None
When the recursion reaches a leaf’s child, root is None. The method immediately returns None, which correctly represents an empty subtree in the trimmed result.
Step 2 - Discarding nodes that are too small
if root.val < low:
return self.trimBST(root.right, low, high)
If the current node’s value is less than the lower bound, the entire left subtree is guaranteed to contain values smaller than low because of the BST invariant. The algorithm therefore discards the left side completely and continues the trim operation on the right child, which may hold values within the desired range.
Step 3 - Discarding nodes that are too large
if root.val > high:
return self.trimBST(root.left, low, high)
Conversely, when the node’s value exceeds the upper bound, the right subtree can be ignored outright. The method recurses on the left child, which is the only side that might contain admissible values.
Step 4 - Preserving nodes that lie inside the interval
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
When the node’s value satisfies low ≤ root.val ≤ high, the node itself is retained. The algorithm then recursively trims both left and right subtrees, reassigning the possibly altered children back to root. Finally, the unchanged node is returned as part of the reconstructed tree.
Edge Cases Addressed
The recursion naturally covers several boundary conditions:
- Empty input tree - The initial
if not rootclause returnsNone, yielding an empty result. - All nodes below the lower bound - The algorithm repeatedly follows the right child until a node meeting the interval is found or the tree is exhausted, ultimately returning
Noneif no such node exists. - All nodes above the upper bound - Symmetrically, the left child is followed until a suitable node is encountered or the tree ends, again resulting in
Nonewhen appropriate. - Values exactly equal to the bounds - The comparison operators are inclusive (
< lowand> high), so nodes whose values equalloworhighare retained, and their subtrees are processed normally. - Highly unbalanced trees - Because the method only traverses branches that could contain valid values, even a degenerate (linked-list-like) BST is handled without unnecessary work.
Performance Optimizations Observed
The implementation exploits the BST ordering to prune entire subtrees in constant time. When a node is outside the interval on one side, the opposite side is never visited, eliminating needless recursive calls. This selective traversal reduces the number of visited nodes to exactly those that could possibly survive the trim, which is the most efficient approach given the problem constraints.
Recursive calls reuse the same self.trimBST method, avoiding the overhead of auxiliary data structures. By directly reassigning the trimmed children back to the current node, the algorithm modifies the tree in place, eliminating the need for additional node allocations or copying. This in-place reconstruction contributes to lower memory pressure and faster execution.
ELI5 - Simplified Explanation
Imagine a big family tree made of numbers. Some numbers are too small because they are lower than the starting point, and some are too big because they are higher than the ending point. This code acts like a tiny gardener that tidies up the tree.
When the gardener looks at a number, it checks if that number is where it belongs. If a number is too small, the gardener ignores it and moves over to the right side where the bigger numbers live. If a number is too big, the gardener leaves it behind and looks at the left side where the smaller numbers are hiding.
If a number is just right, the gardener keeps it but keeps checking the left and right branches to make sure every other number attached to those branches is also following the rules. By the time the gardener is finished, every number left in the tree is perfectly placed between the low number and the high number.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | |||||||||
| leetcode.ca | C++ | Java | Python | JS | C | Rust | Go | TS | |||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 237: Delete Node in a Linked List
- problem 260: Single Number III
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality