深度优先搜索
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/