-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1110-Delete-Nodes-And-Return-Forest.py
39 lines (39 loc) · 1.22 KB
/
1110-Delete-Nodes-And-Return-Forest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
if root is None:
return []
to_delete_map={}
for item in to_delete:
to_delete_map[item]=1
# each node in the tree has a distinct value.
self.ret=[root]
def dfs(node):
if node.val in to_delete_map:
del to_delete_map[node.val]
if node.left:
self.ret.append(node.left)
if node.right:
self.ret.append(node.right)
return True
if node.left:
ret=dfs(node.left)
if ret:
node.left=None
if node.right:
ret=dfs(node.right)
if ret:
node.right=None
idx=0
while to_delete_map:
node=self.ret[idx]
ret=dfs(node)
if ret:
self.ret[idx]=None
idx+=1
return list(filter(lambda x:x,self.ret))