返回其后序遍历: [5,6,3,2,4,1].
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int>res;
if(!root) return res;
for(auto i:root->children)
{
vector<int>tmp =postorder(i);
res.insert(res.end(),tmp.begin(),tmp.end());
}
res.push_back(root->val);
return res;
}
};
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int>res;
if(!root) return res;
stack<Node*>pt;
pt.push(root);
while(!pt.empty())
{
if(pt.top()->children.empty())
{
res.push_back(pt.top()->val);
pt.pop();
if(!pt.empty()) pt.top()->children.erase(pt.top()->children.begin());
}
else{
pt.push(pt.top()->children[0]);
}
}
return res;
}
};