|
| 1 | +## 589. N叉树的前序遍历 |
| 2 | + |
| 3 | +[原题链接](https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/) |
| 4 | + |
| 5 | +### 解一:递归 |
| 6 | + |
| 7 | +```python |
| 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 preorder(self, root: 'Node') -> List[int]: |
| 17 | + res = [] |
| 18 | + self.helper(root, res) |
| 19 | + return res |
| 20 | + |
| 21 | + def helper(self, root, res): |
| 22 | + if root is None: |
| 23 | + return |
| 24 | + res.append(root.val) |
| 25 | + children = root.children |
| 26 | + for child in children: |
| 27 | + self.helper(child, res) |
| 28 | +``` |
| 29 | + |
| 30 | +### 解二:遍历 |
| 31 | + |
| 32 | +用栈辅助。 |
| 33 | + |
| 34 | +1. 首先,将 `root` 压入栈中 |
| 35 | +2. 在栈不为空时,对栈进行遍历,每次弹出栈顶元素 |
| 36 | +3. 若栈顶元素节点不为空,则将该节点值放入结果集中,且将该节点的子节点**从右至左**压入栈中(这样弹出时就是从左至右,符合前序遍历的顺序) |
| 37 | + |
| 38 | +```python |
| 39 | +""" |
| 40 | +# Definition for a Node. |
| 41 | +class Node: |
| 42 | + def __init__(self, val=None, children=None): |
| 43 | + self.val = val |
| 44 | + self.children = children |
| 45 | +""" |
| 46 | +class Solution: |
| 47 | + def preorder(self, root: 'Node') -> List[int]: |
| 48 | + stack = [] |
| 49 | + stack.append(root) |
| 50 | + res = [] |
| 51 | + while len(stack) > 0: |
| 52 | + top = stack.pop() |
| 53 | + if top is None: |
| 54 | + continue |
| 55 | + res.append(top.val) |
| 56 | + # 反序插入子节点 |
| 57 | + children = top.children |
| 58 | + for i in range(len(children) - 1, -1, -1): |
| 59 | + child = children[i] |
| 60 | + stack.append(child) |
| 61 | + return res |
| 62 | +``` |
0 commit comments