给定一个 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 {
public List<Integer> preorder(Node root) {
if(root == null){
return new ArrayList<Integer>();
}
List<Integer> result = new ArrayList<>();
Stack<Node> stack = new Stack<>();
stack.push(root);
while(stack.size()!=0){
Node node = stack.pop();
result.add(node.val);
if(node.children != null){
Collections.reverse(node.children);
for(Node tempNode:node.children){
stack.push(tempNode);
}
}
}
return result;
}
}
递归写法
/*
// 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<>();
public List<Integer> preorder(Node root) {
if(root == null){
return result;
}
result.add(root.val);
for(int i = 0;i < root.children.size();i++){
preorder(root.children.get(i));
}
return result;
}
}