Bird
Raised Fist0
Interview Prepbinary-search-treesmediumAmazonGoogle

Trim a BST

Choose your preparation mode3 modes available
Steps
setup

Initialize root and parameters

The initial BST is constructed with root value 3, and the range [1,3] is set. No pruning has started yet.

💡 Setting up the tree and range is essential before pruning begins.
Line:root = TreeNode(3) root.left = TreeNode(0) root.right = TreeNode(4) low, high = 1, 3
💡 The tree structure and range are now ready for trimming.
📊
Trim a BST - Watch the Algorithm Execute, Step by Step
Watching each pointer move and subtree adjustment helps you understand how BST properties enable efficient pruning without recursion.
Step 1/11
·Active fillAnswer cell
Current node: 0
30421
Current node: 0
30421
Current node: 0
30421
DFS Stack
0 (entered)cur=0
Current node: 0
30421
DFS Stack
0 (left_done)cur=0
Current node: 3
30421
DFS Stack
0 (left_done)cur=3
Current node: 3
30421
DFS Stack
0 (left_done)cur=3
Current node: 4
30421
DFS Stack
0 (left_done)cur=4
Current node: 0
30421
DFS Stack
0 (right_entered)cur=0
Current node: 0
30421
DFS Stack
0 (right_done)cur=0
Current node: 4
30421
DFS Stack
0 (right_done)cur=4
Current node: 0
32104
Return: 0

Key Takeaways

The root is first moved to a valid node within the range before any pruning.

This step ensures the trimmed tree's root is always valid, which is not obvious from code alone.

Left subtree pruning removes nodes less than low by adjusting left pointers iteratively.

Seeing pointer updates visually clarifies how pruning avoids recursion and preserves BST structure.

Right subtree pruning removes nodes greater than high similarly by adjusting right pointers.

The symmetry of left and right pruning is easier to grasp when watching each pointer move.