/*// 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; }};*/classSolution {publicList<Integer> preorder(Node root) {List<Integer> res =newArrayList<>();helper(root, res);return res; }privatevoidhelper(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
classSolution {// preorder is root left right// so use stack we shoud push in right left, // when it pops, it become left rightpublicList<Integer> preorder(Node root) {List<Integer> res =newArrayList<>();Stack<Node> stack =newStack();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; }}