File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(n)
2
+ # Space: O(w)
3
+
4
+ # Given an n-ary tree, return the level order traversal of
5
+ # its nodes' values. (ie, from left to right, level by level).
6
+ #
7
+ # For example, given a 3-ary tree:
8
+ #
9
+ # We should return its level order traversal:
10
+ # [
11
+ # [1],
12
+ # [3,2,4],
13
+ # [5,6]
14
+ # ]
15
+ #
16
+ # Note:
17
+ # - The depth of the tree is at most 1000.
18
+ # - The total number of nodes is at most 5000.
19
+
20
+
21
+ # Definition for a Node.
22
+ class Node (object ):
23
+ def __init__ (self , val , children ):
24
+ self .val = val
25
+ self .children = children
26
+
27
+
28
+ class Solution (object ):
29
+ def levelOrder (self , root ):
30
+ """
31
+ :type root: Node
32
+ :rtype: List[List[int]]
33
+ """
34
+ if not root :
35
+ return []
36
+ result , q = [], [root ]
37
+ while q :
38
+ result .append ([node .val for node in q ])
39
+ q = [child for node in q for child in node .children if child ]
40
+ return result
You can’t perform that action at this time.
0 commit comments