题目链接:
力扣https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
【递归】
class Solution {
public void dfs(Node root, List list){
if(root == null) return;
list.add(root.val);
for(Node node: root.children){
dfs(node, list);
}
}
public List preorder(Node root) {
List list = new ArrayList<>();
dfs(root, list);
return list;
}
}
【迭代】我们发现递归取的时候是先取下一行的第一个,然后插入第一个的所有孩子。所以在第一层的应该把孩子从后往前压入栈,栈顶弹出后再反向插入弹出节点的所有孩子即可。
class Solution {
public List preorder(Node root) {
Stack stack = new Stack<>();
List ans = new ArrayList<>();
if(root == null) return ans;
stack.push(root);
Node cur;
while(!stack.isEmpty()){
cur = stack.pop();
ans.add(cur.val);
for(int i = cur.children.size() - 1; i >= 0; i--){
if(cur.children.get(i) != null) stack.push(cur.children.get(i));
}
}
return ans;
}
}



