Delete Leaves With a Given Value

Given a binary tree root and an integer target, delete all the leaf nodes with value target.

Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted. You need to continue doing this until you cannot delete any more nodes.

Example 1
        1              1
       / \              \
      2   3    ->        3
     /   / \              \
    2   2   4              4
Inputroot = [1,2,3,2,null,2,4], target = 2
Output[1,null,3,null,4]
Leaf nodes with value 2 are removed, and after removal any newly formed leaf nodes with value 2 are also removed.
Example 2
        1                  1
       / \       ->       /
      3   3              3
     / \                  \
    3   2                  2
Inputroot = [1,3,3,3,2], target = 3
Output[1,3,null,null,2]
The leaf nodes with value 3 are deleted, leaving the remaining tree represented as [1,3,null,null,2].

Constraints

  • The number of nodes in the tree is in the range [1, 3000].
  • 1 <= Node.val, target <= 1000

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate