Cascade Deletion of Target-Valued Leaves
Problem statement
Given a binary tree and an integer target, delete every leaf whose value equals target. Repeat this rule when deletion makes another matching node a leaf, until no matching leaf remains. Return the root of the remaining tree.
For this exercise, assume the empty tree remains empty and the root may also be deleted. Preserve the values and relative links of surviving nodes.
Function
removeTargetLeaves(root: TreeNode, target: int) → TreeNodeExamples
Example 1
root = [1,2,3,2,null,2,4]target = 2return = [1,null,3,null,4]Removing matching leaves can expose another removable matching leaf.
Example 2
root = [2,2,2]target = 2return = []The entire tree disappears when every node is removable.
Example 3
root = []target = 2return = []An empty tree remains empty.
Constraints
- For this exercise, assume a finite acyclic binary tree containing
0through500nodes. -10^6 <= node.val <= 10^6. The same bound applies totarget.