FastPrepCascade Deletion of Target-Valued Leaves

Cascade Deletion of Target-Valued Leaves

Microsoft logoMicrosoft● MediumINTERNPHONE SCREEN
Learn

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) → TreeNode

Examples

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 0 through 500 nodes.
  • -10^6 <= node.val <= 10^6. The same bound applies to target.

More Microsoft problems

See Microsoft hiring insights
public TreeNode removeTargetLeaves(TreeNode root, int target) {
    // Write your code here
}
root[1,2,3,2,null,2,4]
target2
expected[1,null,3,null,4]
Checking account…