|
| 1 | +## 429. N叉树的层序遍历 |
| 2 | + |
| 3 | +[原题链接](https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/) |
| 4 | + |
| 5 | +### 解一:迭代 |
| 6 | + |
| 7 | +用队列辅助。 |
| 8 | + |
| 9 | +```python |
| 10 | +""" |
| 11 | +# Definition for a Node. |
| 12 | +class Node: |
| 13 | + def __init__(self, val=None, children=None): |
| 14 | + self.val = val |
| 15 | + self.children = children |
| 16 | +""" |
| 17 | +class Solution: |
| 18 | + def levelOrder(self, root: 'Node') -> List[List[int]]: |
| 19 | + queue = [] |
| 20 | + res = [] |
| 21 | + queue.append(root) |
| 22 | + while len(queue) > 0: |
| 23 | + q_length = len(queue) |
| 24 | + tmp = [] |
| 25 | + for i in range(q_length): |
| 26 | + first = queue[0] |
| 27 | + del queue[0] |
| 28 | + if first is None: |
| 29 | + continue |
| 30 | + tmp.append(first.val) |
| 31 | + for child in first.children: |
| 32 | + queue.append(child) |
| 33 | + if len(tmp) > 0: |
| 34 | + res.append(tmp) |
| 35 | + return res |
| 36 | +``` |
| 37 | + |
| 38 | +- 时间复杂度:$O(n),ドルn 为节点数量 |
| 39 | +- 空间复杂度:$O(n)$ |
| 40 | + |
| 41 | +### 解二:递归 |
| 42 | + |
| 43 | +```python |
| 44 | +""" |
| 45 | +# Definition for a Node. |
| 46 | +class Node: |
| 47 | + def __init__(self, val=None, children=None): |
| 48 | + self.val = val |
| 49 | + self.children = children |
| 50 | +""" |
| 51 | +class Solution: |
| 52 | + def levelOrder(self, root: 'Node') -> List[List[int]]: |
| 53 | + res = [] |
| 54 | + self.helper(res, root, 0) |
| 55 | + return res |
| 56 | + |
| 57 | + def helper(self, res, root, level): |
| 58 | + if root is None: |
| 59 | + return |
| 60 | + if len(res) == level: |
| 61 | + res.append([]) |
| 62 | + res[level].append(root.val) |
| 63 | + for child in root.children: |
| 64 | + self.helper(res, child, level + 1) |
| 65 | +``` |
| 66 | + |
| 67 | +- 时间复杂度:$O(n)$ |
| 68 | +- 空间复杂度:最坏 $O(n),ドル最好 $O(logn)$ |
| 69 | + |
1 | 70 | ## 589. N叉树的前序遍历
|
2 | 71 |
|
3 | 72 | [原题链接](https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/)
|
|
0 commit comments