Delete Leaves With a Target Value
Updated
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]Removed
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]Removed
The left 3 remains because it still has a non-target child.
Example 3
root = [1,2,null,2,null,2]target = 2return = [1]Removed
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.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Maximum Root-to-Leaf and Leaf-to-Leaf Path SumsAmazon · ONSITE INTERVIEW
- Lowest Common Ancestor Only When Both Targets ExistAdobe · ONSITE INTERVIEW
- Sum Root-to-Leaf NumbersMeta · ONSITE INTERVIEW
- Validate Binary Search TreeGoldman Sachs · ONSITE INTERVIEW
- Balanced Tree Node ReportNetflix · ONSITE INTERVIEW
- Trim a Binary Search TreeBloomberg LP · ONSITE INTERVIEW
- Height-Balanced Binary TreeExpedia · ONSITE INTERVIEW
- Binary Tree Target-Sum PathsByteDance · PHONE SCREEN
- Validate Binary Search TreeLyft · PHONE SCREEN
- Lowest Common Ancestor in a Binary TreeZillow · PHONE SCREEN