【问题标题】:Btree with pointers带指针的 Btree
【发布时间】:2015-11-23 11:27:57
【问题描述】:
typedef struct T{ //Main struct of the nodes
     char *value;    //String view like a pointer                                      
     struct T *T_l, *T_r;  //Pointers left and right                                                                                  
}*tree, dim; 

tree mergetree(char *el, tree t1, tree t2){ // Merging sub-btree

     tree t0 = (tree)malloc(sizeof(dim));// Create a struct for merge the sub-btree
     t0->T_l = t1;
     t0->T_r = t2;
     t0->value = el;
     return(t0);
}
tree createleaf(char *el){ //New leaf calling the mergetree function
     return mergetree(el, NULL, NULL);                  

}
int isvoidtree(tree t){ // Checking if the tree is void or not
     return (t == NULL);                                 

}

char *root(tree t){ //Return value of the node

    return t->value;
}

tree leftchild(tree t){ // Return pointer of the node

     return t->T_l;
}
tree rightchild(tree t){ // Return pointer of the node

     return t->T_r;
}

tree insert(char *el, tree t){ //Insert the new element calling specific functions

    if(isvoidtree(t))                                  

        return createleaf(el);
   if (strcmp(root(t), el)>=0)      //Left side                           

       return mergetree(root(t), insert(el, leftchild(t)), rightchild(t)); 
    if (strcmp(root(t),el)<0)  //Right side
             return mergetree(root(t), leftchild(t), insert(el, rightchild(t)));  
    else return t;
}

void showtree(tree t){ //Show recursively the root of all sub-btree
    int i;
    if (isvoidtree(t) == false){ // if the tree is not null the start of recursive calls start
            showtree(leftchild(t));
            printf("%s\n", root(t));
            showtree(rightchild(t));
    }
}

主函数包含初始化类树结构,变量 互动。

int main(int argc, char** argv) {
    int N,i;  
    char el[20];
    tree btree = NULL;  //init btree
    printf("Size:\n");
    scanf("%d",&N);
    for(i=0;i<N;i++){
    printf("Insert name:\n");
    scanf("%s",el);

    btree = insert(el,btree);}

    showtree(btree); //Output btree

    return (EXIT_SUCCESS);
}

你好。以上是我的代码。我的连接有问题 左右两边的树。输出我总是添加最后一个节点 迭代 N 次树有多大。问题似乎出在字符串中。在此先感谢各位。

【问题讨论】:

  • 不要 typedef 指针,除非您将它们用于不透明的数据类型。这掩盖了它们的含义,并使读者感到困惑。并使用“说话”的名字。对于树 node Node 可能是一个不错的选择。

标签: c pointers b-tree


【解决方案1】:

你将每个名字读入同一个数组;因此,树的每个元素都指向同一个字符串,该字符串包含输入的姓氏。正如您为每个新节点分配空间(但未能释放那些您不再使用的节点,唉),您需要为每个名称分配空间。

【讨论】:

  • 嗯,是的。您有解决此问题的实际解决方案吗?
猜你喜欢
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-03
相关资源
最近更新 更多