-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathN-ary Tree Level Order Traversal.py
55 lines (40 loc) · 1.21 KB
/
N-ary Tree Level Order Traversal.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
from collections import defaultdict, deque
from typing import Generator, List, Optional
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def levelOrder(self, root: Optional[Node]) -> List[List[int]]:
if root is None:
return []
queue = deque([root])
levels = []
while queue:
levels.append([])
for _ in range(len(queue)):
node = queue.popleft()
levels[-1].append(node.val)
queue.extend(node.children)
return levels
class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def levelOrder(self, root: Optional[Node]) -> List[List[int]]:
levels = defaultdict(list)
for node, depth in self._walk(root):
levels[node].append(node.val)
return [levels[d] for d in sorted(levels)]
@classmethod
def _walk(cls, root: Optional[Node], depth: int = 0) -> Generator:
if root is None:
return
yield root, depth
for child in root.children:
yield from cls._walk(child, depth + 1)