如何在我的printpostroder函数中访问树?

问题描述

这是我的树结构:

    typedef struct quad 
{
    struct quad *child[4];
    char *names;
} quad;

,我需要先构建它,然后再进行后期打印 但是我无法在我的printpostorder函数中访问树的内存:

void printpostorder(quad * tree)  
    {
       if (tree->names[0] == 'G') {      
        printpostorder(tree->child[0]); 
        printpostorder(tree->child[1]); 
        printpostorder(tree->child[2]); 
        printpostorder(tree->child[3]); 
        
        printf("%s",tree->names);
        }
        else {
        printf("%s",tree->names);
        }
    } 

我可以在主函数调用函数之前对其进行访问。

int main(void){
    
   int n = 0;
   int size;
   quad * t;
   char * str1 = (char *)malloc(MAX * sizeof(char));
   printf("Enter name: ");
   scanf("%s",str1);
   size = strlen(str1);
   t = build_preorder_tree(str1,t,&n,size);
   printpostorder(t);
   
   
}

这是构建树函数,基本上我们必须从预购订单构建,然后打印出后订单。

quad* build_preorder_tree(char *s_r,quad * tree,int * index_ptr,int size){
    
    char c;
    int s = 0;
    int index = *index_ptr;
    c = s_r[index];
    char d = ']';
    char * ptr = (char *)malloc(MAX * sizeof(char));
    char * ptr1;
    
    if(index == size){
        return;
    }
    
    tree = malloc(sizeof(quad*));
    tree -> names = (char *)malloc(MAX * sizeof(char));
    

    if(c == 'G') {
     tree->names = "G";
     (*index_ptr)++;
     tree->child[SW] = build_preorder_tree(s_r,tree->child[SW],index_ptr,size);
     tree->child[SE] = build_preorder_tree(s_r,tree->child[SE],size);
     tree->child[NW] = build_preorder_tree(s_r,tree->child[NW],size);
     tree->child[NE] = build_preorder_tree(s_r,tree->child[NE],size);
     
    } 
    if(c == 'W') {
        tree->names = "W";
        (*index_ptr)++;
    }
    if(c == 'B') {
        strcpy(ptr,s_r);
        ptr1 = strtok(ptr+index,"]");
        strncat(ptr1,&d,1);
        s = strlen(ptr1);
        (*index_ptr)= (*index_ptr) + s;
        tree->names  = ptr1;
        
    }
    
     
    
 return tree;
 
}

当我调用printpostorder(t)时,第一次调用时发生段错误 if (tree->names[0] == 'G')

调用printpostorder之前,我尝试访问树,并且能够访问树的每个元素

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)