589. N叉树的前序遍历
深度优先搜索
class Solution {
List<Integer> list = new LinkedList<>();
public List<Integer> preorder(Node root) {
if (root == null){
return list;
}
list.add(root.val);
for (Node c : root.children){
preorder(c);
}
return list;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
迭代
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> list = new LinkedList<>();
Stack<Node> stack = new Stack<>();
if (root == null){
return list;
}
stack.push(root);
while (!stack.isEmpty()){
Node temp = stack.pop();
list.add(temp.val);
for (int i = temp.children.size() - 1; i >= 0; i--) {
stack.push(temp.children.get(i));
}
}
return list;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/

浙公网安备 33010602011771号