> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/tree/589.-n-ary-tree-preorder-traversal.md).

# 589. N-ary Tree Preorder Traversal

{% embed url="<https://leetcode.com/problems/n-ary-tree-preorder-traversal/>" %}

recursion

```java
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    public List<Integer> preorder(Node root) {
        List<Integer> res = new ArrayList<>();
        helper(root, res);

        return res;
        
    }
    
    private void helper(Node root, List<Integer> res) {
        if (root == null) {
            return;
        }
        res.add(root.val);

        for (Node d : root.children) {
            helper(d, res);
        }
    }

}
```

iteration

use stack,  see the comment

放入stack right left, 這樣pop時就會是 left right

也 就是 root left right

```java

class Solution {
    // preorder is root left right
    // so use stack we shoud push in right left, 
    // when it pops, it become left right
    public List<Integer> preorder(Node root) {
        List<Integer> res = new ArrayList<>();
        Stack<Node> stack = new Stack();
        
        stack.push(root);
        
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            if (node != null) {
                res.add(node.val);
                for (int i = node.children.size() - 1; i >= 0; i--) {
                    stack.push(node.children.get(i));
                }
            }
        }
        return res;
    }
}
```
