Delete Leaves With a Given Value

Given the `root` of a binary tree and an integer `target`, delete every leaf node whose value is `target`. After a leaf with value `target` is deleted, its parent may become a leaf. If that parent also has value `target`, it must be deleted too. Keep going until no such leaf remains, and return the root (which may be `null`).

30:00

Delete Leaves With a Given Value
medium
Free written solution
Topics
Companies

Given the root of a binary tree and an integer target, delete every leaf node whose value is target.

After a leaf with value target is deleted, its parent may become a leaf. If that parent also has value target, it must be deleted too. Keep going until no such leaf remains, and return the root (which may be null).

Example 1:
Input: {"root":[1,2,3,2,null,2,4],"target":2}
Output: [1,null,3,null,4]
Constraints:
  • The number of nodes in the tree is in the range [1,3000][1, 3000].

  • 1≤1 \le Node.val, target ≤1000\le 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,2,3,2,null,2,4],"target":2}

Delete leaves equal to 2, bottom-up: a node is judged only after its children, so a parent that becomes a leaf is caught in the same pass. 3 of 6 nodes hold 2.

target = 2
deleted 0
cascade 0
stack: (empty)
123224

deleted, in order

none yet
value 2
recursion stack
kept
deleted leaf
deleted after becoming a leaf
Variables
VariableValue
nodes6
target2
matches3
DepthFunction Call
Stack empty
0/13