#1325
Delete Leaves With a Given Value
MediumTreeDepth-First SearchBinary TreeDepth-First Search (DFS)Tree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(h) |
💡
Intuition
Time O(n)Space O(h)
The optimal solution also uses DFS but ensures that we only traverse the tree once. We check each node and its children, and if a child is a leaf with the target value, we remove it. This way, we efficiently handle the cascading deletions.
⚙️
Algorithm
5 steps- 1Step 1: Start DFS from the root node.
- 2Step 2: Recursively check the left and right children.
- 3Step 3: If a child is a leaf node with the target value, return null to its parent.
- 4Step 4: If the current node has no children left and its value equals target, return null.
- 5Step 5: Otherwise, return the current node.
solution.py15 lines
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode:
9 if not root:
10 return None
11 root.left = self.removeLeafNodes(root.left, target)
12 root.right = self.removeLeafNodes(root.right, target)
13 if root.val == target and not root.left and not root.right:
14 return None
15 return rootℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
- 1Recursive tree traversal is essential for tree problems.
- 2Understanding leaf nodes and their properties is crucial for this problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.