FunctionRacerProblemsRace

Binary Tree Pruning

MediumTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. Every node holds 0 or 1. Remove every subtree that contains no 1 at all (so every remaining leaf holds a 1, but inner nodes may hold 0). Return the root of the pruned tree; if no node holds a 1, the result is empty.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [1,null,0,0,1]
returns [1,null,0,null,1]

The left 0 under the 0 goes away; the 1 under it stays: [1,None,0,None,1].

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems