【发布时间】:2016-08-27 14:52:57
【问题描述】:
我刚开始学习树并使用 c 语言实现它。我想我为树(二叉搜索树)制作了程序但是在搜索值并打印是否找到元素时,搜索函数没有正确返回值(或错误值) 特此附上代码
// to search in binary search tree
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct bstnode
{
int data;
struct bstnode *left;
struct bstnode *right;
};
struct bstnode *insert(struct bstnode *,int);
int search(struct bstnode *,int);
void main()
{
int n,s,n1;
char ch;
struct node *root;
clrscr();
root=NULL;
do
{
printf("\nEnter a number\n");
scanf("%d",&n);
root=insert(root,n);
printf("\nDo You Wish to enter more\n");
ch=getch();
} while(ch=='Y'||ch=='y');
printf("Enter a number to search");
scanf("%d",&n1);
s=search(root,n1);
if(s==1)
printf("Found");
else
printf("Not found");
getch();
}
struct bstnode* insert(struct bstnode *root,int data)
{
struct bstnode *newnode=(struct bstnode*)malloc(sizeof(struct bstnode));
newnode->data=data;
newnode->left=NULL;
newnode->right=NULL;
if(root==NULL)
{
root=newnode;
}
else if(data<=root->data)
{
root->left=insert(root->left,data);
}
else
{
root->right=insert(root->right,data);
}
return(root);
}
int search(struct bstnode* root,int data)
{
if(root==NULL)
return 0;
if(root->data==NULL)
return 1;
else if(data<=root->data)
return(root->left,data);
else
return(root->right,data);
}
请帮忙!!!!
【问题讨论】:
-
用调试器单步调试你的代码,看看哪里出错了。
-
你认为
return(root->left, data)会做什么?您需要递归调用search函数,但您只是返回data。 -
if (root->data == NULL)是错误的。data是int,NULL应该与指针一起使用。 -
@Barmar 我已经纠正了这个错误,但我的问题仍然没有解决
-
根指针的类型应该是 struct bstnode*
标签: c data-structures tree binary-search-tree