C 二叉搜索树打印值

时间:2020-12-22 14:49:09

标签: c binary-tree

我有这个程序,它从用户那里获取 6 个数字并创建二叉搜索树。它工作正常,但当我尝试打印它时,它会打印一个随机数。

25 37 48 66 70 82 11098240 这是打印出来的值,不知道是我的打印功能还是插入功能有问题。有什么帮助吗?

    #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;
    }

1 个答案:

答案 0 :(得分:1)

你从来没有在顶层分配 Tree->val,所以它有未初始化的垃圾。

不要创建第一棵树。就这样做:

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