# 589. N-ary Tree Preorder Traversal

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/n-ary-tree-preorder-traversal/

> 内容描述

```
Given an n-ary tree, return the preorder traversal of its nodes' values.

For example, given a 3-ary tree:

 



 

Return its preorder traversal as: [1,3,5,6,2,4].

 

Note:

Recursive solution is trivial, could you do it iteratively?
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

递归，beats 74.77%

```python
class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """ 
        if not root:
            return []
        res = []
        res.append(root.val)
        for child in root.children:
            res.extend(self.preorder(child))
        return res
```

> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

迭代，beats 95.28%

```python
class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        if not root:
            return []
        res, stack = [], [root]
        while stack:
            node = stack.pop()
            res.append(node.val)
            for child in node.children[::-1]:
                stack.append(child)
        return res
```

