给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树
:
返回其前序遍历: [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 {
ArrayList<Integer> list = new ArrayList();
public List<Integer> preorder(Node root) {
helper(root);
return list;
}
public void helper(Node root) {
if(root == null) {
return;
}
list.add(root.val);
int s = root.children.size();
for(int i = 0; i < s; i++) {
helper(root.children.get(i));
}
}
}
来源:CSDN
作者:PJJ彭彭彭
链接:https://blog.csdn.net/qq_37822034/article/details/104025014