0

I tried binary tree data structure but found it to be not working and giving an error. Please correct my code. Thanks!

It gives warning but with the inputs in main it stops running .

#include<stdlib.h>
#include<stdio.h>
typedef struct
{
    int item;
    struct node * leftc;
    struct node * rightc;
}node;

void create(int key, node **tree )
{
    if(*tree ==0)
    {
        (*tree)= (node *)malloc(sizeof(node *));
        (*tree)->item=key;
        (*tree)->leftc=((*tree)->rightc)=NULL;
    } 
    else
{
    if(key >= (*tree)->item )
    {
        create(key, &((*tree)->rightc));
    }
    else if(key<(*tree)->item)
    {
        create(key, &((*tree)->leftc));
    }
}
}

node * search(int key, node * tree)
{
    if(tree !=NULL)
    {
      if(key == tree->item)
        return tree;
      else if(key > tree->item)
        search(key, tree->rightc);
      else
        search(key, tree->leftc);
    }
  return NULL;
}

void cut(node * tree)
{
  if(tree != NULL)
  {
    cut(tree->leftc);
    cut(tree->rightc);
    free(tree);
  }
}

void print_preorder(node * tree)
{
if (tree) {
 printf("%d\n",tree->item);
 print_preorder(tree->leftc);
 print_preorder(tree->rightc);
}
}


int main()
{
   node * root=NULL;
 create(9,&root);
 create(16,&root);
 create(24,&root);
 create(6,&root);

 return 0;

}
4

2 回答 2

0

改变

typedef struct
{
    int item;
    struct node * leftc;
    struct node * rightc;
}node;

typedef struct node
{
    int item;
    struct node * leftc;
    struct node * rightc;
}node;

在您的结构中,您引用“结构节点”,因此您需要名称才能正确引用自身。当然,在 typedef 之后,您可以将其称为节点。

测试程序使用另外给出的代码编译并运行良好。

于 2013-06-26T19:39:57.697 回答
0

我知道这不能回答您关于错误的问题,但我注意到您的search()功能存在一个主要问题。如果它是第一个放入函数的节点,则仅返回要查找的节点。递归调用search()不返回任何内容。该函数应如下所示:

node * search(int key, node * tree)
{
    if (tree !=NULL)
    {
        if (key == tree->item) {
            return tree;
        } else if (key > tree->item) {
            return search(key, tree->rightc);
        } else if (key < tree->item) {
            return search(key, tree->leftc);
        }
    }
    return NULL;
}

另外,在您的create()功能中,您的意思是检查if (*tree == NULL)而不是if (*tree == 0)

于 2013-06-26T19:18:48.417 回答