给定一个 n 叉树的根节点 root ,返回 其节点值的 后序遍历 。
n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。
输入:root = [1,null,3,2,4,null,5,6]
输出:[5,6,3,2,4,1]
输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[2,6,14,11,7,3,12,8,4,13,9,10,5,1]
解题代码如下:
/**
* Definition for a Node.
* struct Node {
* int val;
* int numChildren;
* struct Node** children;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void behind_tra(struct Node* root,int *b,int *r){
if(root){
if(root->numChildren==0){
b[*r]=root->val;
(*r)++;
return ;
}
else{
int i=0;
for(;i<root->numChildren;i++){
behind_tra(root->children[i],b,r);
}
}
b[*r]=root->val;
(*r)++;
}
}
int* postorder(struct Node* root, int* returnSize) {
int *b=(int *)malloc(sizeof(int)*10000);
int *r=(int *)malloc(sizeof(int));
*r=0;
behind_tra(root,b,r);
*returnSize=*r;
return b;
}