给定一个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,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
List<Integer> result = new ArrayList<Integer>();
public List<Integer> preorder(Node root) {
if (root == null) return result;
preOrderNarrTree(root);
return result;
}
private void preOrderNarrTree(Node root) {
result.add(root.val);
for (Node chil : root.children) {
preOrderNarrTree(chil);
}
}
}
网友评论