|
| 1 | +""" |
| 2 | +Given an n-ary tree, return the level order traversal of its nodes' values. |
| 3 | + |
| 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 | +""" |
| 6 | + |
| 7 | +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 | +class Solution: |
| 16 | + def levelOrder(self, root: 'Node') -> List[List[int]]: |
| 17 | + # Base Condition |
| 18 | + if root is None: |
| 19 | + return [] |
| 20 | + |
| 21 | + q = deque() |
| 22 | + # Append the trees root |
| 23 | + q.append(root) |
| 24 | + # Separator - Separates Levels of the Tree |
| 25 | + sep = '$' |
| 26 | + # Append the separator - means end of root level |
| 27 | + q.append(sep) |
| 28 | + |
| 29 | + # Appending root.val to answer |
| 30 | + ans = [[root.val]] |
| 31 | + |
| 32 | + # Previous to check if all nodes are visited. Used to break while loop below |
| 33 | + prev = -1 |
| 34 | + # A temporary list to store all nodes of each level |
| 35 | + temp = [] |
| 36 | + while q: |
| 37 | + # Pop the first element of the deque |
| 38 | + curr = q.popleft() |
| 39 | + # If curr is not ,ドル the we add it's children(the next level) one by one to the deque and temp list as well. |
| 40 | + if curr and curr != sep: |
| 41 | + for i in curr.children: |
| 42 | + q.append(i) |
| 43 | + temp.append(i.val) |
| 44 | + elif curr == sep: |
| 45 | + # if curr == ,ドル that means we have reached the end of a level, so append temp list to answer. |
| 46 | + q.append(sep) |
| 47 | + if temp: |
| 48 | + ans.append(list(temp)) |
| 49 | + temp = [] |
| 50 | + |
| 51 | + # Exit conditon. If curr == prev and they are both ,ドルmeans we have completed traversing all levels |
| 52 | + if prev == curr and curr == sep: |
| 53 | + break |
| 54 | + |
| 55 | + # Updating the prev with curr |
| 56 | + prev = curr |
| 57 | + |
| 58 | + |
| 59 | + return ans |
| 60 | + |
0 commit comments