# #LeetCode刷题之#589-N叉树的前序遍C历（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?

```public class Program {

public static void Main(string[] args) {
var root = new Node(1,
new List<Node> {
new Node(3, new List<Node> {
new Node(5, null),
new Node(6, null)
}),
new Node(2, null),
new Node(4, null)
});

var res = Preorder(root);
ShowArray(res);

res = Preorder2(root);
ShowArray(res);

}

private static void ShowArray(IList<int> array) {
foreach(var num in array) {
Console.Write(\$"{num} ");
}
Console.WriteLine();
}

public static IList<int> Preorder(Node root) {
var list = new List<int>();
Pre(root, ref list);
return list;
}

public static void Pre(Node root, ref List<int> list) {
if(root == null) return;
if(root.children == null) return;
foreach(var child in root.children) {
Pre(child, ref list);
}
return;
}

public static IList<int> Preorder2(Node root) {
var list = new List<int>();
if(root == null) return list;
var stack = new Stack<Node>();
stack.Push(root);
while(stack.Any()) {
var pop = stack.Pop();
if(pop.children != null) {
for(var i = pop.children.Count() - 1; i >= 0; i--)
stack.Push(pop.children[i]);
}
}
return list;
}

public class Node {
public int val;
public IList<Node> children;
public Node() { }
public Node(int _val, IList<Node> _children) {
val = _val;
children = _children;
}
}

}```

```1 3 5 6 2 4
1 3 5 6 2 4```