LeetCode 1325: Delete Leaves With a Given Value Solution
Master LeetCode problem 1325 (Delete Leaves With a Given Value), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1325. Delete Leaves With a Given Value
Problem Explanation
Explanation:
To solve this problem, we can perform a depth-first search (DFS) on the binary tree. At each node, we recursively check its left and right children. If a child is a leaf node and has the value equal to the target, we can remove that child by setting it to null. We continue this process until no more leaf nodes with the target value exist.
Algorithm:
- Recursively traverse the tree using DFS.
- For each node, check if its left and right children are leaf nodes with the target value.
- If a child is a leaf node with the target value, set that child to null.
- Repeat this process until no more leaf nodes with the target value exist.
Time Complexity:
The time complexity for this approach is O(n), where n is the number of nodes in the binary tree.
Space Complexity:
The space complexity is also O(n) due to the recursive stack space used during the DFS traversal.
: :
Solution Code
class Solution {
public TreeNode removeLeafNodes(TreeNode root, int target) {
if (root == null) {
return null;
}
root.left = removeLeafNodes(root.left, target);
root.right = removeLeafNodes(root.right, target);
if (root.left == null && root.right == null && root.val == target) {
return null;
}
return root;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1325 (Delete Leaves With a Given Value)?
This page provides optimized solutions for LeetCode problem 1325 (Delete Leaves With a Given Value) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1325 (Delete Leaves With a Given Value)?
The time complexity for LeetCode 1325 (Delete Leaves With a Given Value) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1325 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1325 in Java, C++, or Python.