LeetCode Solutions

590. N-ary Tree Postorder Traversal

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  vector<int> postorder(Node* root) {
    if (root == nullptr)
      return {};

    vector<int> ans;
    stack<Node*> stack{{root}};

    while (!stack.empty()) {
      root = stack.top(), stack.pop();
      ans.push_back(root->val);
      for (Node* child : root->children)
        stack.push(child);
    }

    reverse(begin(ans), end(ans));
    return ans;
  }
};
			

class Solution {
  public List<Integer> postorder(Node root) {
    if (root == null)
      return new ArrayList<>();

    List<Integer> ans = new ArrayList<>();
    Deque<Node> stack = new ArrayDeque<>();
    stack.push(root);

    while (!stack.isEmpty()) {
      root = stack.pop();
      ans.add(root.val);
      for (Node child : root.children)
        stack.push(child);
    }

    Collections.reverse(ans);
    return ans;
  }
}