Binary Tree Pruning - Problem
Imagine you have a binary tree where each node contains either 0 or 1. Your task is to prune this tree by removing all subtrees that don't contain at least one 1.
Think of it like trimming a plant - you want to cut off all the branches that don't have any fruit (represented by 1s). A subtree is considered "fruitless" if it contains only 0s.
What you need to do:
- Given the root of a binary tree with
0s and1s - Remove every subtree that contains only
0s - Return the pruned tree
- A subtree includes a node and all its descendants
Key insight: If a subtree has no 1s anywhere in it, the entire subtree should be removed!
Input & Output
example_1.py โ Basic Tree Pruning
$
Input:
[1,null,0,0,1]
โบ
Output:
[1,null,0,null,1]
๐ก Note:
The left subtree of the right child (which was [0,0,null]) contained only zeros and was pruned. The right child itself (0) was kept because its right subtree contains a 1.
example_2.py โ Root Pruning
$
Input:
[1,0,1,0,0,0,1]
โบ
Output:
[1,null,1,null,1]
๐ก Note:
The entire left subtree [0,0,0] contained only zeros and was pruned. From the right subtree, only the path leading to 1 was preserved.
example_3.py โ Complete Tree Removal
$
Input:
[0,0,0]
โบ
Output:
[]
๐ก Note:
The entire tree contains only zeros, so everything gets pruned, resulting in an empty tree (null root).
Visualization
Tap to expand
Understanding the Visualization
1
Start at Leaves
Begin at the bottom of the tree, examining leaf nodes first
2
Remove Zero Leaves
Cut off any leaf nodes that contain 0 (no fruit)
3
Move Up Tree
After pruning children, examine parent nodes
4
Prune Empty Branches
If a node has value 0 and no children left, remove it too
5
Preserve Paths to 1s
Keep any branch that leads to a 1, even if it contains 0s along the way
Key Takeaway
๐ฏ Key Insight: Post-order traversal ensures we process children before parents, allowing optimal pruning decisions in a single pass through the tree.
Time & Space Complexity
Time Complexity
O(n)
Visit each node exactly once in post-order traversal
โ Linear Growth
Space Complexity
O(h)
Recursion stack depth equals tree height h, O(log n) for balanced tree, O(n) for skewed tree
โ Linear Space
Constraints
- The number of nodes in the tree is in the range [1, 200]
- Node.val is either 0 or 1
- Key constraint: Only subtrees containing exclusively 0s should be pruned
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code