题目描述
iven an n-ary tree, return the preorder traversal of its nodes’ values.
For example, given a 3-ary tree:
Return its preorder traversal as: [1,3,5,6,2,4].
Note:
Recursive solution is trivial, could you do it iteratively?
方法思路
Approach1: recursive
class Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> preorder(Node root) {
if(root == null) return res;
res.add(root.val);
for(Node child : root.children)
preorder(child);
return res;
}
}
Approach2: iteratively based on stack
class Solution {
//Runtime: 7 ms, faster than 16.71%
public List<Integer> preorder(Node root) {
List<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
Stack<Node> stack = new Stack<Node>();
stack.add(root);
while(!stack.isEmpty()){
Node node = stack.pop();
res.add(node.val);
for(int i = node.children.size()-1;i >= 0;i--){
stack.add(node.children.get(i));
}
}
return res;
}
}