Problem Description
Given the root of a binary tree where each node is either 0 or 1, remove every subtree that does not contain a 1. A subtree is defined as a node plus all its descendants. The pruned tree should only contain nodes which are either 1 or have at least one descendant with a 1.
Key Insights
- Use a postorder DFS traversal so that you process the children before the parent.
- At each node, recursively check and prune the left and right subtrees.
- If a node’s left and right subtrees are pruned away (i.e. become null) and the node’s value is 0, prune the node itself.
- The process simultaneously checks for the condition and rebuilds the tree by linking only necessary nodes.
Space and Time Complexity
Time Complexity: O(n) where n is the number of nodes in the tree, since every node is visited once. Space Complexity: O(n) in the worst case due to recursion stack space in the case of a skewed tree.
Solution
The solution employs a recursive postorder DFS that processes the left and right subtrees first, then checks the current node. For each node, if both left and right subtrees do not contain 1 (i.e., have been pruned to null) and the current node’s value is 0, the current node is pruned by returning null. This approach ensures that the tree is pruned from the bottom up, preserving nodes that are required to satisfy the condition that at least one node in the subtree has a value of 1.