题目


思路
迭代
class Solution {
public List<Integer> postorder(Node root) {
LinkedList<Integer> res = new LinkedList<>();
if (root == null) return res;
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node cur = stack.pop();
res.addFirst(cur.val);
for (int i = 0; i < cur.children.size(); i++) {
stack.push(cur.children.get(i));
}
}
return res;
}
}
递归
class Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> postorder(Node root) {
dfs(root);
return res;
}
public void dfs(Node root) {
if (root == null) {
return;
}
for (Node node : root.children) {
dfs(node);
}
res.add(root.val);
}
}