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
Binary Tree Pruning INPUT Original Binary Tree 1 null 0 0 1 [1, null, 0, 0, 1] Contains 1 Only 0s (prune) ALGORITHM STEPS 1 Post-Order DFS Visit left, right, then node 2 Process Children First Recursively prune subtrees 3 Check Prune Condition node.val==0 AND no children? 4 Remove or Keep Return null or node Pruning Order: 1 0 1 1st 2nd 3rd X Prune (0, no children) OK Keep (has 1) OK Keep (has 1) FINAL RESULT Pruned Binary Tree 1 null 0 1 null 0 PRUNED Output: [1, null, 0, null, 1] Key Insight: Post-order traversal (left --> right --> root) ensures we process children BEFORE parents. A node can be pruned only if: (1) its value is 0, AND (2) both children are null/pruned. Time: O(n) | Space: O(h) where h = tree height (recursion stack) TutorialsPoint - Binary Tree Pruning | DFS Post-Order Traversal
Asked in
Facebook 25 Amazon 18 Google 15
125.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen