590 - N-ary Tree Postorder Traversal
JAVA
class Solution {
public List<Integer> postorder(Node root) {
LinkedList<Integer> ans = new LinkedList<>();
if (root == null) {
return ans;
}
Deque<Node> stk = new ArrayDeque<>();
stk.offer(root);
while (!stk.isEmpty()) {
root = stk.pollLast();
ans.addFirst(root.val);
for (Node child : root.children) {
stk.offer(child);
}
}
return ans;
}
}C++
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int> ans;
if (!root) return ans;
stack<Node*> stk{ {root} };
while (!stk.empty()) {
root = stk.top();
ans.push_back(root->val);
stk.pop();
for (Node* child : root->children) stk.push(child);
}
reverse(ans.begin(), ans.end());
return ans;
}
};
Comments
Post a Comment