589. N-ary Tree Preorder Traversal

recursion

/*
// 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

Last updated

Was this helpful?