Leetcode 1325: Delete Leaves With a Given Value

grid47
grid47
Exploring patterns and algorithms
Jun 27, 2024 5 min read

You are given the root of a binary tree and an integer target. Your task is to remove all leaf nodes that have the value equal to the target. Once you remove a leaf node with the target value, if its parent node becomes a leaf node and has the same value, it should also be removed. This process should continue until no more leaf nodes with the target value are present.
Problem
Approach
Steps
Complexity
Input: The input consists of the binary tree root represented by a TreeNode object and an integer target. Each node in the binary tree contains a value, left, and right child pointers.
Example: For root = [1,2,3,2,null,2,4] and target = 2, the tree has nodes with values 1, 2, 3, and 4, and we need to remove all leaf nodes with the value 2.
Constraints:
• 1 <= Node.val, target <= 1000
• The number of nodes in the tree is in the range [1, 3000].
Output: The output is the root of the binary tree after removing all leaf nodes with the target value. The tree should still be valid after removal.
Example: For root = [1,2,3,2,null,2,4] and target = 2, the output is [1,null,3,null,4], as all the leaf nodes with value 2 are removed.
Constraints:
Goal: The goal is to traverse the binary tree and remove all leaf nodes with the target value. Once a node is removed, check if its parent node becomes a leaf with the target value and remove it as well.
Steps:
• 1. Traverse the tree recursively.
• 2. At each node, check if it has left or right children.
• 3. If a node is a leaf (both children are null) and its value matches the target, remove it.
• 4. After removing a leaf, check if its parent has become a leaf and has the target value, and repeat the process.
• 5. Return the root of the modified tree.
Goal: The problem guarantees valid tree input values and provides constraints on the number of nodes and values.
Steps:
• 1 <= Node.val, target <= 1000
• 1 <= number of nodes <= 3000
Assumptions:
• The tree is a valid binary tree.
• The value of target is within the bounds of valid node values.
Input: For root = [1,2,3,2,null,2,4] and target = 2, the output is [1,null,3,null,4].
Explanation: The leaf nodes with value 2 are removed. After that, the parent nodes 1 and 3 are left as the final tree.

Input: For root = [1,3,3,3,2] and target = 3, the output is [1,3,null,null,2].
Explanation: Leaf nodes with value 3 are removed and the remaining tree is adjusted accordingly.

Input: For root = [1,2,null,2,null,2] and target = 2, the output is [1].
Explanation: All leaf nodes with value 2 are removed in a step-by-step manner, leaving only the root node 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus