Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6b95d67

Browse files
committed
O(n) time and O(n) using recursive stack
1 parent f7cdfd7 commit 6b95d67

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
Given a binary tree root and an integer target, delete all the leaf nodes with value target.
3+
4+
Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).
5+
6+
7+
8+
Example 1:
9+
10+
11+
12+
Input: root = [1,2,3,2,null,2,4], target = 2
13+
Output: [1,null,3,null,4]
14+
Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left).
15+
After removing, new nodes become leaf nodes with value (target = 2) (Picture in center).
16+
Example 2:
17+
18+
19+
20+
Input: root = [1,3,3,3,2], target = 3
21+
Output: [1,3,null,null,2]
22+
Example 3:
23+
24+
25+
26+
Input: root = [1,2,null,2,null,2], target = 2
27+
Output: [1]
28+
Explanation: Leaf nodes in green with value (target = 2) are removed at each step.
29+
30+
31+
Constraints:
32+
33+
The number of nodes in the tree is in the range [1, 3000].
34+
1 <= Node.val, target <= 1000
35+
"""
36+
37+
38+
# Definition for a binary tree node.
39+
# class TreeNode:
40+
# def __init__(self, val=0, left=None, right=None):
41+
# self.val = val
42+
# self.left = left
43+
# self.right = right
44+
class Solution:
45+
def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:
46+
if root.left: root.left = self.removeLeafNodes(root.left, target)
47+
if root.right: root.right = self.removeLeafNodes(root.right, target)
48+
return None if not root.left and not root.right and root.val == target else root

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /