2016-05-20 8 views
-5
#include<stdlib.h> 
#include<stdio.h> 

struct tree{char info;struct tree *left;struct tree *right;}; 
struct tree *root; 
struct tree *stree(struct tree *root,struct tree *r,char info); 
void print_tree(struct tree *root,int l); 

int main(void) 
{ 
    char s[80]; 
    root=NULL; 
    do { 
    printf("enter a letter:"); 
    gets(s); 
    root=stree(root,root, *s); 

    } 
    while(*s); // <- ??? 
    print_tree(root,0); 
    return 0; 

} 

struct tree *stree(struct tree *root,struct tree *r,char info;{ // <- ??? 
    if(!r) { 
    r=(struct tree *) malloc(sizeof(struct tree)); 
    if(!r) { 
     printf("out of memory \n"); 
     exit(0); 
    } 
    r->left=NULL; 
    r->right=NULL; 
    r->info=info; 
    if(!root) 
    return r; 
    if(info<root->info) 
    root->left=r; 
    else 
    root->right=r; 
    return r;}if(info<r->info)stree(r,r->left,info);else 
    stree(r,r->right,info);return root;} 
    void print_tree(struct tree *r,int l); 
    { 
    int i; 
    if(!r) return ; 
    print_tree(r->right,l+1); 
    for(i=0;i<l;++i) 
    printf(" "); 
    printf("%c \n",r->info); 
    print_tree(r->left,l+1); 
    } 
+2

さて、デバッガでコードをステップ実行しましたか?それが最初のことです。プログラムのデバッグ方法を学ぶことは、言語を学ぶことと同じくらい重要です。また、読みやすいようにコードを適切にインデントしてください。 – OldProgrammer

+1

Q:どのコンパイラとどのデバッガを使用していますか? * FIRST *を試してみるには、デバッガを1行ずつステップ実行して、 "すべてがOK"になっていることを確認してください。 – paulsm4

+3

インデントが... –

答えて

0

戻り値がstreeで更新されていないため、私の推測は正しい出力ではありません。

など。 if(info<r->info)stree(r,r->left,info); < - 戻り値は破棄されました。

コードはコンパイルされません。だから、私はコードを書き直す。

#include <stdio.h> 
#include <stdlib.h> 

struct tree { 
    char info; 
    struct tree *left, *right; 
}; 

struct tree *stree(struct tree *root, char info);//no need `struct tree *r` 
void print_tree(struct tree *root, int level); 

int main(void){ 
    struct tree *root = NULL;//It does not need to be in a global variable 
    char letter; 

    for(;;){ 
     printf("enter a letter:"); 
     if(EOF == scanf("%c", &letter) || letter == '\n')//don't use `gets` 
      break; 
     scanf("%*[^\n]");//clear upto newline 
     scanf("%*c"); 
     root = stree(root, letter); 
    } 
    print_tree(root, 0); 
    //deallocate 
    return 0; 

} 

struct tree *stree(struct tree *root, char info){ 
    if(!root){ 
     struct tree *r = malloc(sizeof(*r)); 
     if(!r){ 
      fprintf(stderr, "out of memory\n"); 
      exit(EXIT_FAILURE); 
     } 
     r->right = r->left = NULL; 
     r->info = info; 
     return r; 
    } 
    if(info < root->info) 
     root->left = stree(root->left, info); 
    else if(info > root->info) 
     root->right = stree(root->right, info); 
    else 
     ;//root->right = stree(root->right, info); 
    return root; 
} 

void print_tree(struct tree *r, int level){ 
    if(!r) return ; 

    print_tree(r->right, level + 1); 

    printf("%*s%c\n", level, "", r->info); 

    print_tree(r->left, level + 1); 
} 
関連する問題