题目链接:https://leetcode.com/problems/n-ary-tree-postorder-traversal/
题面:
590. N-ary Tree Postorder Traversal
Easy
29137FavoriteShare
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叉树。
解题:
1.递归最简单;
2.不递归,用栈实现即可,先进后出。
代码:
class Solution {
public:
vector<int> postorder(Node* root) {
vector <int> res;
vector <int> temp;
if(root==NULL)return res;
for(int i=0;i<root->children.size();i++){
temp=postorder(root->children[i]);
for(int j=0;j<temp.size();j++)
res.push_back(temp[j]);
}
res.push_back(root->val);
return res;
}
};