[英]C Binary Search Tree Printing Values
I have this program which gets 6 numbers from user and creates binary search tree.我有这个程序,它从用户那里获取 6 个数字并创建二叉搜索树。 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. 25 37 48 66 70 82 11098240 这是打印出来的值,我不知道问题出在我的打印 function 还是插入 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.您永远不会在顶层分配 Tree->val,因此它具有未初始化的垃圾。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.