FunctionRacerProblemsRace

Remove Leaves With a Given Value

MediumTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. Delete every leaf whose value equals target. If that makes a parent into a leaf holding target, delete it as well, and keep going until no such leaf is left. Return the root (the tree may become 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,2,3,2,null,2,4]
target 2
returns [1,null,3,null,4]

Both leaves 2 go; then the 2 under the root becomes a leaf and goes; the other 2 goes too: [1,None,3,None,4].

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