Delete Leaves With a Given Value

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree and an integer target, delete every leaf whose value equals target. Deleting leaves can turn their parent into a new leaf. If that parent also has value target, it must be deleted too, and so on until no leaf with value target remains. Return the root of the resulting tree, or an empty tree (serialized as []) if every node is deleted.

Examples

Input: root = [1,2,3,2,null,2,4], target = 2
Output: [1,null,3,null,4]
The 2-leaves go first, which leaves the left child 2 as a leaf, so it is deleted as well.
Input: root = [1,3,3,3,2], target = 3
Output: [1,3,null,null,2]
Only the 3-leaves are removed; the inner 3 still has the child 2.
Input: root = [1,1,1], target = 1
Output: []
Removing both leaves exposes the root as a leaf with value 1.

Constraints

  • 1 <= number of nodes <= 3000
  • 1 <= Node.val, target <= 1000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems