【问题标题】:Search function is not returning the value搜索功能没有返回值
【发布时间】: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-&gt;left, data) 会做什么?您需要递归调用search 函数,但您只是返回data
  • if (root-&gt;data == NULL) 是错误的。 dataintNULL 应该与指针一起使用。
  • @Barmar 我已经纠正了这个错误,但我的问题仍然没有解决
  • 根指针的类型应该是 struct bstnode*

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


【解决方案1】:

你的search函数有两个问题:

  1. 它从不检查是否找到data。相反,它会检查 root-&gt;data == NULL,但这是不正确的。
  2. 它应该在左子树或右子树上递归调用自己,但事实并非如此。

正确的代码是:

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

【讨论】:

  • 谢谢,现在你已经解决了我的问题,再次感谢,请继续帮助我
  • 我希望你多学习,这样你就不必来这里让其他人为你调试你的程序了。如果你不学习,你永远不会成为一名程序员。
猜你喜欢
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多