Problem 669

Abstract / Summary

Remove nodes from a binary search tree so every value stays within a given range.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
13 lines | 467 bytes | submitted September 4, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 root clause returns None, 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 None if 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 None when appropriate.
  • Values exactly equal to the bounds - The comparison operators are inclusive (< low and > high), so nodes whose values equal low or high are 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.96 | σ = 1.57

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
41 links | 25 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

4 easy 20 medium
25 solutions   September 4, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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