forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
delete-tree-nodes.py
45 lines (39 loc) · 1.18 KB
/
delete-tree-nodes.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
40
41
42
43
44
45
# Time: O(n)
# Space: O(n)
import collections
class Solution(object):
def deleteTreeNodes(self, nodes, parent, value):
"""
:type nodes: int
:type parent: List[int]
:type value: List[int]
:rtype: int
"""
def dfs(value, children, x):
total, count = value[x], 1
for y in children[x]:
t, c = dfs(value, children, y)
total += t
count += c if t else 0
return total, count if total else 0
children = collections.defaultdict(list)
for i, p in enumerate(parent):
if i:
children[p].append(i)
return dfs(value, children, 0)[1]
# Time: O(n)
# Space: O(n)
class Solution2(object):
def deleteTreeNodes(self, nodes, parent, value):
"""
:type nodes: int
:type parent: List[int]
:type value: List[int]
:rtype: int
"""
# assuming parent[i] < i for all i > 0
result = [1]*nodes
for i in reversed(xrange(1, nodes)):
value[parent[i]] += value[i]
result[parent[i]] += result[i] if value[i] else 0
return result[0]