forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-nodes-with-value-one.py
78 lines (64 loc) · 1.71 KB
/
number-of-nodes-with-value-one.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# Time: O(q + n)
# Space: O(n)
import collections
# bfs
class Solution(object):
def numberOfNodes(self, n, queries):
"""
:type n: int
:type queries: List[int]
:rtype: int
"""
def bfs():
result = 0
q = [(1, 0)]
while q:
new_q = []
for u, curr in q:
curr ^= cnt[u]%2
result += curr
for v in xrange(2*u, min(2*u+1, n)+1):
q.append((v, curr))
q = new_q
return result
cnt = collections.Counter(queries)
return bfs()
# Time: O(q + n)
# Space: O(q + logn)
import collections
# iterative dfs
class Solution2(object):
def numberOfNodes(self, n, queries):
"""
:type n: int
:type queries: List[int]
:rtype: int
"""
def iter_dfs():
result = 0
stk = [(1, 0)]
while stk:
u, curr = stk.pop()
curr ^= cnt[u]%2
result += curr
for v in reversed(xrange(2*u, min(2*u+1, n)+1)):
stk.append((v, curr))
return result
cnt = collections.Counter(queries)
return iter_dfs()
# Time: O(q + n)
# Space: O(q + logn)
import collections
# dfs
class Solution3(object):
def numberOfNodes(self, n, queries):
"""
:type n: int
:type queries: List[int]
:rtype: int
"""
def dfs(u, curr):
curr ^= cnt[u]%2
return curr+sum(dfs(v, curr) for v in xrange(2*u, min(2*u+1, n)+1))
cnt = collections.Counter(queries)
return dfs(1, 0)