思路:类似于二叉树的排序,这里需要将子树进行依次递归遍历,前序遍历也与之类似
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
//用于保存结果
vector<int> res;
vector<int> postorder(Node* root) {
helper(root);
return res;
}
//递归函数
void helper(Node* root){
//如果节点为空
if(root == nullptr) return;
//获取当前节点的子节点
vector<Node*> children = root->children;
//依次递归调用叶子节点
for(int i = 0;i<children.size();i++){
helper(children[i]);
}
res.push_back(root->val);
}
};