Grokking Tree Coding Patterns for Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Delete Leaves With a Given Value (medium)
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

Given a root node of a binary tree and an integer target, delete all leaf nodes that have a value equal to target.

After removing such leaf nodes, if any of their parent nodes become leaf nodes with a value equal to target, they should also be removed. This process should continue until no more nodes can be deleted.

Examples

Example 1

  • Input: root = [1, 5, 3, 5, null, 5, 4], Target: 5 here:
Image
  • Expected Output: [1,null,3,null,4]
  • Explanation: The left child of 5 (left of root) is 3 and 5. When we remove both leaf having value 5, the left node of the root also becomes a leaf having a value equal to 5. So, we also remove it.

Example 2

  • Input: root = [3, 3, 3, 3, 3, null, 4], Target: 3
Image
  • Expected Output: [3,null,3,null,4]
  • Explanation: Remove all 3 except the root and right child of the root node.

Example 3

  • Input: root = [4, 5, 6, 5, null, 7, 8], Target: 5
Image
  • Expected Output: [4,null,6,7,8]
  • Explanation: The leaf nodes with value 5 are removed first. The tree becomes [4, 5, 6, null, null, 7, 8]. Now, again remove the leaf node with the value 5 and the tree becomes [4, null, 6, 7, 8]`.

Constraints:

  • The number of nodes in the tree is in the range [1, 3000].
  • 1 <= Node.val, target <= 1000

Try it yourself

Try solving this question

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible