Skip to content

Commit 1402575

Browse files
authored
Create n-ary-tree-level-order-traversal.py
1 parent 63f92ca commit 1402575

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

0 commit comments

Comments
 (0)