2016-07-14 5 views
1

Я написал программу C для ввода элементов двоичного дерева поиска и отображения его обходов InOrder, PostOrder и PreOrder.Inorder, Preorder and Postorder traversals

#include<stdio.h> 
#include<stdlib.h> 
struct tnode 
{ 
    int data; 
    struct tnode *leftc; 
    struct tnode *rightc; 
}; 
int main() 
{ 
    char ans='N'; 
    struct tnode *new_node,*root; 
    // struct tnode *get_node(); 
    root=NULL; 
    do{ 
     // new_node=get_node(); 
     printf("\nEnter the Element"); 
     scanf("%d",&new_node->data); 
     if(root==NULL) 
      root=new_node; 
     else 
      insert(root,new_node); 
     printf("\nDo you want to enter a new element?(y/n)"); 
     scanf("%c",&ans); 
    }while(ans == 'y'); 
    printf("Inorder traversal:the elements in the tree are"); 
    inorder(root); 
    printf("\nPreorder traversal:the elements in the tree are"); 
    preorder(root); 
    printf("Postorder traversal:the elements in the tree are"); 
    postorder(root); 
    return 0; 
} 
void insert(struct tnode ** tree,int num) 
{ 
    struct tnode *temp = NULL; 
    if(!(*tree)) 
    { 
     temp=(struct tnode *)malloc(sizeof (struct tnode)); 
     temp->leftc=temp->rightc=NULL; 
     temp->data=num; 
     *tree=temp; 
     return; 
    } 
    if(num < (*tree)->data) 
    { 
     insert(&(*tree)->leftc,num); 
    } 
    else if(num > (*tree)->data) 
    { 
     insert(&(*tree)->rightc,num); 
    } 
} 
void preorder(struct tnode * s) 
{ 
    if(s) 
    { 
     printf("%d\n",s->data); 
     preorder(s->leftc); 
     preorder(s->rightc); 
    } 
} 
void inorder(struct tnode * s) 
{ 
    if(s) 
    { 
     inorder(s->leftc); 
     printf("%d\n",s->data); 
     inorder(s->rightc); 
    } 
} 
void postorder(struct tnode * s) 
{ 
    if(s) 
    { 
     postorder(s->leftc); 
     postorder(s->rightc); 
     printf("%d\n",s->data); 
    } 
} 

Я получаю эти предупредительные сообщения:

warning: implicit declaration of functionS, 
conflicting types OF FUNCTIONS, 
new_node’ may be used uninitialized in this function 

Я не могу понять errors.Can вы помочь мне исправить это?

+3

Пожалуйста, выравнивал код, в противном случае я не смотрел на нее. –

+2

Не смотрел код, но касался первого предупреждения: в C вы должны объявить функции перед использованием термодатчика. На самом деле вы должны объявить * все *, прежде чем использовать его. Что касается другого, инициализируйте переменную 'new_node', прежде чем использовать ее? –

ответ

3

В C для того, чтобы использовать функцию вам необходимо объявить им, прежде, чем основной функции, как в вашем случае, вы должны написать:

void insert(struct tnode ** tree,int num); 
//all declarations of other functions here . 

// Кстати вы можете объявить им, без имен переменных, как это:

void insert(struct tnode ** , int); 

также просто попробуйте Google Двоичное дерево поиска в C. Существует множество веб-сайтов, которые показывают именно тот ответ, который вы ищете, и множество веб-сайтов, на которых есть учебники, которые объясняют все вокруг.

P.S Если вы не хотите объявлять функции перед основной функцией, вы можете просто поставить готовые функции, которые у вас есть сверху главной и основной функции, должны быть внизу в конце.

2
  • Вы должны объявить или определить функции использовать перед тем вы используете их.
  • Неверное использование insert().
  • Использование значения неинициализированной переменной с длительностью автоматического хранения, которая является неопределенной, вызывает неопределенное поведение. В этом случае вам не нужно использовать struct для чтения данных для нового узла.
  • То, что вы не ожидаете, может быть прочитано в ans. Добавьте пробел перед спецификатором формата %c, чтобы иметь scanf() Пропустить пробел перед чтением персонажа.
  • Вы должны использовать одну из стандартных подписей main(). В C, int main() и int main(void)have different meanings.
  • Вы должны правильно отформатировать свой код.
  • Говорят, you shouldn't cast the result of malloc() in C.

Попробуйте это:

#include<stdio.h> 
#include<stdlib.h> 
struct tnode 
{ 
    int data; 
    struct tnode *leftc; 
    struct tnode *rightc; 
}; 
/* declare functions */ 
void insert(struct tnode ** tree,int num); 
void preorder(struct tnode * s); 
void inorder(struct tnode * s); 
void postorder(struct tnode * s); 
/* use one of the standard forms of main() */ 
int main(void) 
{ 
    char ans='N'; 
    struct tnode *root; 
    int new_node_data; 
    // struct tnode *get_node(); 
    root=NULL; 
    do{ 
     // new_node=get_node(); 
     printf("\nEnter the Element"); 
     scanf("%d",&new_node_data); /* do not dereference indeterminate pointer */ 
     insert(&root,new_node_data); /* pass correct data */ 
     printf("\nDo you want to enter a new element?(y/n)"); 
     scanf(" %c",&ans); /* add a space before %c to have scanf() skip whitespace characters */ 
    }while(ans == 'y'); 
    printf("Inorder traversal:the elements in the tree are"); 
    inorder(root); 
    printf("\nPreorder traversal:the elements in the tree are"); 
    preorder(root); 
    printf("Postorder traversal:the elements in the tree are"); 
    postorder(root); 
    return 0; 
} 
void insert(struct tnode ** tree,int num) 
{ 
    struct tnode *temp = NULL; 
    if(!(*tree)) 
    { 
     temp=malloc(sizeof (struct tnode)); 
     temp->leftc=temp->rightc=NULL; 
     temp->data=num; 
     *tree=temp; 
     return; 
    } 
    if(num < (*tree)->data) 
    { 
     insert(&(*tree)->leftc,num); 
    } 
    else if(num > (*tree)->data) 
    { 
     insert(&(*tree)->rightc,num); 
    } 
} 
void preorder(struct tnode * s) 
{ 
    if(s) 
    { 
     printf("%d\n",s->data); 
     preorder(s->leftc); 
     preorder(s->rightc); 
    } 
} 
void inorder(struct tnode * s) 
{ 
    if(s) 
    { 
     inorder(s->leftc); 
     printf("%d\n",s->data); 
     inorder(s->rightc); 
    } 
} 
void postorder(struct tnode * s) 
{ 
    if(s) 
    { 
     postorder(s->leftc); 
     postorder(s->rightc); 
     printf("%d\n",s->data); 
    } 
} 
+0

спасибо за помощь .. но на выходе только первый элемент печатается для всех трех обходов – joejoe

+0

@joejoe [Невозможно воспроизвести] (http://melpon.org/wandbox/permlink/DeQ813IWJy5Y6Bib). – MikeCAT