/* // 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 { List<Integer> list = new LinkedList<>(); public List<Integer> preorder(Node root) { if (root == null) return list; list.add(root.val); for (Node node : root.children) preorder(node); return list; } }
class Solution { List<Integer> list = new LinkedList<>(); public List<Integer> preorder(Node root) { List<Integer> list = new LinkedList<>(); if (root == null) return list; Stack<Node> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { Node node = stack.pop(); list.add(node.val); Collections.reverse(node.children); for (Node item : node.children) { stack.push(item); } } return list; } }