搜索功能未返回值

时间:2016-08-27 14:52:57

标签: c data-structures tree binary-search-tree

我刚刚开始学习树,并使用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);
}

请帮助!!!!

1 个答案:

答案 0 :(得分:1)

您的search函数有两个问题:

  1. 它永远不会检查是否找到data。相反,它会检查root->data == NULL,但这不正确。
  2. 它应该在左侧或右侧子树上递归调用,但它不是。
  3. 正确的代码是:

    int search(struct bstnode* root,int data)
    {
        if(root==NULL) {
            return 0;
        } else if(root->data==data) {
            return 1;
        } else if(data<=root->data) {
            return search(root->left,data);
        } else {
            return search(root->right,data);
        }
    }
    
相关问题