Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0862048

Browse files
authored
Update Day-6_N-ary Tree Level Order Traversal.py
1 parent 2c9034f commit 0862048

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

‎Leetcode_30day_challenge/August_Challenge_2021/Day-6_N-ary Tree Level Order Traversal.py‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,8 @@
44
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
55
"""
66

7+
# Solution - 1
78
from collections import deque
8-
"""
9-
# Definition for a Node.
10-
class Node:
11-
def __init__(self, val=None, children=None):
12-
self.val = val
13-
self.children = children
14-
"""
159
class Solution:
1610
def levelOrder(self, root: 'Node') -> List[List[int]]:
1711
# Base Condition
@@ -58,3 +52,22 @@ def levelOrder(self, root: 'Node') -> List[List[int]]:
5852

5953
return ans
6054

55+
56+
57+
# Solution - 2 Pythonic Way
58+
from collections import deque
59+
class Solution:
60+
def levelOrder(self, root: 'Node') -> List[List[int]]:
61+
# Base Condition
62+
if root is None:
63+
return []
64+
# Append the root to deque
65+
q = deque([root])
66+
ans = []
67+
while q:
68+
# Append the list of nodes present in the deque
69+
ans.append([node.val for node in q])
70+
# Update/Append the Deque with the list of nodes from the next level.
71+
q = [node for nodes in q for node in nodes.children if node]
72+
73+
return ans

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /