|
4 | 4 | Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). |
5 | 5 | """ |
6 | 6 |
|
| 7 | +# Solution - 1 |
7 | 8 | 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 | | -""" |
15 | 9 | class Solution: |
16 | 10 | def levelOrder(self, root: 'Node') -> List[List[int]]: |
17 | 11 | # Base Condition |
@@ -58,3 +52,22 @@ def levelOrder(self, root: 'Node') -> List[List[int]]: |
58 | 52 |
|
59 | 53 | return ans |
60 | 54 |
|
| 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