题目:
给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树 :
返回其前序遍历: [1,3,5,6,2,4]。
说明: 递归法很简单,你可以使用迭代法完成此题吗?
解法1:递归
/**
* 思路:
* 先把当前节点加到结果集中
* 之后看每层的节点是否有children,有就继续进行递归
*/
public List<Integer> preorder(Node root) {
ArrayList<Integer> result = new ArrayList<>();
recursive(result,root);
return result;
}
private void recursive(ArrayList<Integer> result, Node root) {
if (root==null)return;
result.add(root.val);
if (root.children!=null) {
for (Node n : root.children) {
recursive(result, n);
}
}
}
时间复杂度:On
空间复杂度:On
解法2:stack
/**
* 思路:
* stack
* 把每层的节点从右到左的顺序入栈
*/
public List<Integer> preorder(Node root) {
LinkedList<Integer> result = new LinkedList<Integer>();
if (root==null)return result;
ArrayDeque<Node> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()){
Node pop = stack.pop();
result.add(pop.val);
if (pop.children!=null) {
Collections.reverse(pop.children);
for (Node node : pop.children) {
stack.push(node);
}
// int size = pop.children.size();
// for (int i=size-1;i>=0;i--){
// stack.push(pop.children.get(i));
// }
}
}
return result;
}
时间复杂度:On^2
空间复杂度:On