hardTreesPure DSA~25 min
Prune Subtrees That Contain No One
In a binary tree of 0/1 flags, remove every subtree that does not contain a single 1. Return the pruned tree.
Problem
Given the root of a binary tree where each node's value is 0 or 1, prune the tree: remove every subtree not containing a 1. Return the resulting root (possibly null).
Input
A binary tree root with 0/1 node values.
Output
The pruned tree root.
Constraints
- 1 <= number of nodes <= 200
- node value is 0 or 1.
- Pruning is recursive: a node is removed if its whole subtree is zeros.
Examples
Example 1
Input
root = [1,null,0,0,1]
Output
[1,null,0,null,1]
The all-zero subtree is removed; the branch with a 1 stays.
Example 2
Input
root = [1,0,1,0,0,0,1]
Output
[1,null,1,null,1]
Every all-zero subtree is pruned.