Given an n-ary tree, return the postorder traversal of its nodes' values.
For example, given a 3-ary tree:
Return its postorder traversal as: [5,6,3,2,4,1].
Note:
Recursive solution is trivial, could you do it iteratively?
Related Topics:
Tree
Similar Questions:
- Binary Tree Postorder Traversal (Hard)
- N-ary Tree Level Order Traversal (Easy)
- N-ary Tree Preorder Traversal (Easy)
// OJ: https://leetcode.com/problems/n-ary-tree-postorder-traversal/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(logN)
class Solution {
private:
vector<int> ans;
void rec(Node *root) {
if (!root) return;
for (auto ch : root->children) rec(ch);
ans.push_back(root->val);
}
public:
vector<int> postorder(Node* root) {
rec(root);
return ans;
}
};Preorder traverse the mirrored tree and reverse the result!
// OJ: https://leetcode.com/problems/n-ary-tree-postorder-traversal/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(logN)
class Solution {
public:
vector<int> postorder(Node* root) {
if (!root) return {};
stack<Node*> s;
s.push(root);
vector<int> ans;
while (s.size()) {
root = s.top();
s.pop();
ans.push_back(root->val);
for (auto c : root->children) s.push(c);
}
reverse(ans.begin(), ans.end());
return ans;
}
};