简体   繁体   中英

C Binary Search Tree Printing Values

I have this program which gets 6 numbers from user and creates binary search tree. It works fine but when I try to print it, it prints one random number.

25 37 48 66 70 82 11098240 This is the printed values, I don't know if the problem is with my print function or insert function. Any help?

    #include <stdio.h>
    #include <stdlib.h>
    
    struct Node
    {
      int val;
      struct Node* left;
      struct Node* right;
    };
    typedef struct Node *Tree;        
    
    void DisplayTree(Tree t)
    {
        if(t == NULL)
            return;
        DisplayTree(t->left);
        printf("%d\n", t->val);
        DisplayTree(t->right);
    }
    
    Tree InsertElement(int val, Tree t)
    {
        if(t == NULL){
            Tree root  = (struct Node*)malloc(sizeof(struct Node));
            root->left = NULL;
            root->right = NULL;
            root->val = val;
            return root;
        }
        if(t->val < val)
        {
            t->right = InsertElement(val, t->right);
            return t;
        }
        t->left = InsertElement(val, t->left);
        return t;
    }
    
    Tree CreateTree()
    {
        int i;
        int val;
        Tree Temp = (struct Node*)malloc(sizeof(struct Node));
        Temp->left = NULL;
        Temp->right = NULL;
        for(i=0;i<6;i++)
        {
            scanf("%d", &val);
            InsertElement(val, Temp);
        }
        return Temp;
    }
    
    int main()
    {
        Tree myTree = CreateTree();
    
        DisplayTree(myTree);
    
        return 0;
    }

You never assign Tree->val at the top level, so it has uninitialized garbage.

Don't create that first tree. Just do:

Tree                                                                               
CreateTree()                                                                       
{                                                                                  
        int val;                                                                   
        Tree Temp = NULL;                                                          
        while( scanf("%d", &val) == 1 ){                                           
                Temp = InsertElement(val, Temp);                                   
        }                                                                          
        return Temp;                                                               
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM