589. N叉树的前序遍历

题解:
思路一:

递归

代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
ArrayList list = new ArrayList();
public List<Integer> preorder(Node root) {
    if (root == null) return list;
    
    Node node = root;
    list.add(node.val);

    for (int i = 0; i < root.children.size(); i++){
        
        preorder(node.children.get(i));
    }
    
    return list;
}
思路二:

迭代 , 跟二叉树前序遍历相同.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public List<Integer> preorder(Node root) {
    if (root == null) return list;

    Stack<Node> stack = new Stack<>();
    stack.push(root);

    while (!stack.isEmpty()){

        Node node = stack.pop();
        list.add(node.val);

        for (int i = node.children.size() - 1; i >= 0; i--) {
            stack.push(node.children.get(i));
        }
    }

    return list;
}