Skip to content
Problem 814 · LeetCode 814(opens in a new tab)

Binary Tree Pruning

MediumDepth-first search

You are given the root of a binary tree in which every node holds 0 or 1.

Remove every subtree that contains no 1 at all, and return the root of what is left. If the whole tree has no 1, return an empty tree.

Example 1

Input:  root = [1, 0, 1, 0, 1, null, 0]
Output: [1, 0, 1, null, 1]
Why:    both bottom 0s are cut; the 0 above a 1 stays
2 more examples and the constraints

Example 2

Input:  root = [0, 0, 0]
Output: []
Why:    there is no 1, so even the root goes

Example 3

Input:  root = [0, null, 1]
Output: [0, null, 1]
Why:    the 0 root has a 1 below it, so it stays

Constraints

  • 1 ≤ number of nodes ≤ 200
  • Every node’s value is 0 or 1

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Search each subtree for a 1O(n²)
  2. Post-order: prune children firstO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 200-node chainVerdict
Search each subtreeO(n²)
Passes; repeats every search
Post-order pruningO(n)
Best; one visit per node

n = number of nodes, h = height of the tree. Trees are written in level order, with null for a missing child.

Edge cases to test

  • No 1 anywhere. Return an empty tree, not a lone 0 root.
  • A 0 above a 1. It stays, because its subtree holds a 1.
  • A 0 whose children are all 0. It goes, but only after its children have gone.
  • A tall chain. 200 nodes in a line means recursion 200 deep, which is fine.

Common mistakes

  • Checking a node before pruning its children, so a 0 above two all-zero subtrees stays.
  • Pruning the children but not storing the result back in left and right.
  • Returning the original root even when the whole tree was cut.

How to talk through it

  1. 1Clarify. What should come back if no node is 1? Can I change the tree in place?
  2. 2Give the direct version. Search each subtree for a 1; say the repeated searches make it O(n²).
  3. 3Flip the order. Let children report back first: post-order makes it one pass.
  4. 4Code it. Assign the pruned children, then return null for a 0 leaf.
  5. 5Test out loud. Run an all-zero tree and a 0 root with a single 1 below.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?