【LeetCode】590. N-ary Tree Postorder Traversal
题目链接:https://leetcode.com/problems/n-ary-tree-postorder-traversal/
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?
N叉树的后序遍历。
方法一递归:
class Solution {
public:
vector<int> ans;
vector<int> postorder(Node* root) {
if(!root)return ans;
for(int i=0;i<root->children.size();i++){
postorder(root->children[i]);
}
ans.push_back(root->val);
return ans;
}
};
题目中Note说能不能用迭代去做,所以又研究了一下迭代的方法。
方法二:
class Solution {
public:
vector<int> ans;
vector<int> postorder(Node* root) {
stack<Node*> stk;
if(!root)return ans;
stk.push(root);
while(!stk.empty()){
Node* nod=stk.top();
stk.pop();
int len=nod->children.size();
for(int i=0;i<len;i++){
stk.push(nod->children[i]);
}
ans.push_back(nod->val);
}
reverse(ans.begin(),ans.end());
return ans;
}
};