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


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;
    }
}

Last updated