本题也是树的遍历, 只不过把二叉树换成了 N 叉树, 其实背后的思想还是一样的. 也用递归和非递归来实现一下 :
我的思路
递归思路
class Solution {
private List<Integer> result = new LinkedList<>();
public List<Integer> preorder(Node root) {
if (root != null) {
result.add(root.val);
int size = root.children.size();
for(int i = 0; i < size; i++) {
preorder(root.children.get(i));
}
}
return result;
}
}
上面的对当前结点的子结点进行递归函数的调用, 其实也就是一个遍历过程, 可以用下面的方式表示 :
class Solution {
private List<Integer> result = new LinkedList<>();
public List<Integer> preorder(Node root) {
if (root != null) {
result.add(root.val);
for(Node node : root.children) {
preorder(node);
}
}
return result;
}
}
非递归思路
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> result = new LinkedList<>();
if (root == null)
return result;
Stack<Node> nodes = new Stack<>();
nodes.add(root);
while(!nodes.isEmpty()) {
Node curr = nodes.pop();
result.add(curr.val);
int size = curr.children.size();
for(int i = size; i > 0; i--) {
nodes.add(curr.children.get(i - 1));
}
}
return result;
}
}
非递归是用栈来实现的, 所以这里需要注意的是, 栈的特点是先进后出, 所以在遍历的时候, 先调用递归函数来遍历当前结点靠右的子结点.