Binary Tree Pruning - Problem
Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
A subtree of a node node is node plus every node that is a descendant of node.
Input & Output
Example 1 — Binary Tree with Mixed Values
$
Input:
root = [1,null,0,0,1]
›
Output:
[1,null,0,null,1]
💡 Note:
The left subtree (null) is already empty. In the right subtree, the node with value 0 at position [1][0] has a left child 0 (no 1s) which gets removed, but keeps the right child 1. Final tree: [1,null,0,null,1]
Example 2 — Complete Removal
$
Input:
root = [1,0,1,0,0,0,1]
›
Output:
[1,null,1,null,1]
💡 Note:
Left subtree has only 0s, so it's completely removed. Right subtree keeps the path to the 1. The 0 nodes without 1s in their subtrees are pruned away.
Example 3 — All Zeros Except Root
$
Input:
root = [1,1,0,1,1,0,1,0]
›
Output:
[1,1,0,1,1,null,1]
💡 Note:
Most nodes have value 1 so they're kept. Only the leaf nodes with 0 that don't lead to any 1s are removed.
Constraints
- The number of nodes in the tree is in the range [1, 200]
- Node.val is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with 0s and 1s: [1,0,1,0,0,0,1]
2
Identify Subtrees
Find subtrees that contain no 1s (should be removed)
3
Pruned Result
Tree after removing subtrees: [1,null,1,null,1]
Key Takeaway
🎯 Key Insight: Use post-order traversal to decide about each node after processing its children - keep nodes that have value 1 OR have remaining children
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code