590. N叉树的后序遍历
作者:互联网
深度优先搜索
class Solution {
List<Integer> list = new LinkedList<>();
public List<Integer> postorder(Node root) {
if (root == null){
return list;
}
for (Node c : root.children){
postorder(c);
}
list.add(root.val);
return list;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
迭代
class Solution {
public List<Integer> postorder(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 (Node c : root.children){
stack.push(c);
}
}
Collections.reverse(list);
return list;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
标签:Node,590,遍历,return,后序,复杂度,list,root,stack 来源: https://www.cnblogs.com/taoyuann/p/15918889.html