题目链接https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/


解题代码
/*
// 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> postorder(Node* root) {
vector<int> postNums;
post(root, postNums);
return postNums;
}
void post(Node* root, vector<int>& nums){
if(root==NULL){
return;
}
if(root->children.size()!=0){
int n = root->children.size();
for(int i=0; i<n; i++){
post(root->children[i], nums);
}
}
nums.push_back(root->val);
}
};
运行结果

本文解析了LeetCode上的N-ary树后序遍历问题,通过实例展示了如何使用递归方法实现Node类,并提供了完整的解题代码。理解并掌握后序遍历对于深入理解树形数据结构至关重要。
660

被折叠的 条评论
为什么被折叠?



