N-ary Tree Preorder Traversal N叉树前序遍历
给一个N叉树的root,返回其前序遍历
输入:root = [1,null,3,2,4,null,5,6]
输出:[1,3,5,6,2,4]
/*
// 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 {
void _preorder(Node root,List<Integer> ans){
if(root == null){
return;
}
ans.add(root.val);
for (int i = 0; i <root.children.size() ; i++) {
_preorder(root.children.get(i),ans);
}
return;
}
public List<Integer> preorder(Node root) {
List<Integer> ans = new ArrayList<>();
_preorder(root,ans);
return ans;
}
}
Tag
tree
recursion