Magicsheet logo

Delete Leaves With a Given Value

Medium
25%
Updated 8/1/2025

Delete Leaves With a Given Value

1. What is this problem about?

The Delete Leaves With a Given Value interview question is a classic tree manipulation challenge. You are given the root of a binary tree and a target integer value. Your task is to remove all leaf nodes that contain this target value. The trickiest part of this Delete Leaves With a Given Value coding problem is that once a leaf is removed, its parent might become a new leaf. If this new leaf also contains the target value, it must also be deleted. This process continues until no more qualifying leaves exist in the tree.

2. Why is this asked in interviews?

Companies like Amazon and Google frequently ask this question to test a candidate's understanding of Binary Tree interview patterns, specifically recursive traversals. It evaluates your ability to manage parent-child pointers and handle cascading changes within a data structure. It's an excellent test of "bottom-up" thinking, where decisions at the lower levels of the tree affect the structure of the upper levels.

3. Algorithmic pattern used

This problem is best solved using the Post-order Traversal (Depth-First Search) pattern. By visiting the left and right children before the parent node, you can ensure that by the time you process a node, its qualifying children have already been deleted. This allows the current node to correctly identify itself as a potential leaf.

4. Example explanation

Imagine a tree where the root is 1, its left child is 2, and its right child is 3. Both children 2 and 3 have their own children with the value 2. Target value is 2.

  1. We go deep into the left subtree. We find a leaf node 2. We delete it.
  2. The parent of that deleted node was 2. Now that its child is gone, this parent 2 is a leaf.
  3. Because we are using post-order DFS, we check this new leaf 2. Since it matches the target, we delete it too.
  4. Finally, we return to the root 1. Its left child is now null.

5. Common mistakes candidates make

  • Using Pre-order traversal: Trying to delete nodes from the top down. This won't work because you don't know if a node will become a leaf until its children are processed.
  • Forgetting the cascading effect: Only deleting the original leaves and failing to delete nodes that become leaves during the process.
  • Not handling the root: Failing to return the updated root, which could potentially be null if the entire tree consisted of target-value leaves.

6. Interview preparation tip

Whenever you encounter a tree problem where changes at the bottom affect the structure above, think of Post-order DFS. Practice writing recursive functions that return the updated node reference; this is a very common and powerful pattern for tree modification tasks.

Similar Questions