Given an N-ary tree, whose nodes preorder traversal return value.
For example, given a tree 3:
Before returning to their preorder traversal: [1,3,5,6,2,4].
Ideas:
All issues and tree-related, can be solved by recursion
递归4部曲
- Recursive exit conditions
- Processing the current layer
- Deal with the next layer
- Cleanup current layer
answer:
/*
// 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 {
ArrayList result=new ArrayList();
public List<Integer> preorder(Node root) {
if(root==null){
return new ArrayList();
}
result.add(root.val);
for(Node child: root.children){
preorder(child);
}
return result;
}
}