题目详述
给定一个 N 叉树,返回其节点值的后序遍历。
解法一
递归。时间复杂度:O(n),空间复杂度O(logn)
class Solution {
public List<Integer> postorder(Node root) {
List<Integer> ans = new ArrayList<>();
helper(root, ans);
return ans;
}
public void helper(Node root, List ans) {
if (root == null) return;
int s = root.children.size();
for (int i = 0; i < s; i++) helper(root.children.get(i), ans);
ans.add(root.val);
}
}
解法二
迭代。时间复杂度:O(n),空间复杂度:O(n)
class Solution {
public List<Integer> postorder(Node root) {
if (root == null) return new ArrayList();
Stack<Node> stack = new Stack<>();
LinkedList<Integer> list = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
Node node = stack.pop();
list.addFirst(node.val);
for (Node temp : node.children)
if (temp != null) stack.push(temp);
}
return list;
}
}