Delete Leaves With a Target Value
Problem statement
Given a binary tree and an integer target, repeatedly delete every leaf whose value equals target. After deletions, a parent may become a new target-valued leaf and must also be deleted.
Return the final root. Modify and reuse the surviving input nodes.
Function
removeLeafNodes(root: TreeNode, target: int) → TreeNodeExamples
Example 1
root = [1,2,3,2,null,2,4]target = 2return = [1,null,3,null,4]All target-valued leaves are removed, including the left child after its child disappears.
Example 2
root = [1,3,3,3,2]target = 3return = [1,3,null,null,2]The left 3 remains because it still has a non-target child.
Example 3
root = [1,2,null,2,null,2]target = 2return = [1]Deletion cascades upward through the chain of 2-valued nodes.
Example 4
root = []target = 1return = []An empty tree remains empty.
Constraints
- The tree contains between
0and100000nodes. -10^9 <= node.val, target <= 10^9.