Skip to content

Commit d7d17fe

Browse files
committed
Add Solution.py to problems 1110
1 parent 167e713 commit d7d17fe

File tree

1 file changed

+55
-0
lines changed
  • solution/1110.Delete Nodes And Return Forest

1 file changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
'''
2+
https://leetcode.com/problems/delete-nodes-and-return-forest/
3+
Given the root of a binary tree, each node in the tree has a distinct value.
4+
5+
After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).
6+
7+
Return the roots of the trees in the remaining forest. You may return the result in any order.
8+
9+
'''
10+
# Performance
11+
'''
12+
Runtime: 52 ms, faster than 99.34% of Python3 online submissions for Delete Nodes And Return Forest.
13+
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Delete Nodes And Return Forest.
14+
'''
15+
'''
16+
n: number of node
17+
m: number of to_delete
18+
Runtime: O(n)
19+
Space: O(log n) or O(m)
20+
'''
21+
22+
23+
class Solution:
24+
def delNodes(self, root, to_delete):
25+
# Change to set to for better check runtime
26+
set_delete = set(to_delete)
27+
forests = []
28+
# Only add a node in the forest when
29+
# 1) Its parent is in set_delete
30+
# 2) It's not in set_delete
31+
# dfs return False when 1) Node is none and 2) node is in set_delete
32+
# When that happen, set the parent link to that node to None
33+
34+
def dfs(node, is_parent_in_delete):
35+
nonlocal set_delete, forests
36+
if not node:
37+
return False
38+
# Still traverse subsequent node but return False
39+
if node.val in set_delete:
40+
if node.left:
41+
dfs(node.left, True)
42+
if node.right:
43+
dfs(node.right, True)
44+
return False
45+
# Add the current node to the forest
46+
if is_parent_in_delete:
47+
forests.append(node)
48+
# Set the child to none when the child is in set_delete
49+
if node.left and not dfs(node.left, False):
50+
node.left = None
51+
if node.right and not dfs(node.right, False):
52+
node.right = None
53+
return True
54+
dfs(root, True)
55+
return forests

0 commit comments

Comments
 (0)