c++ - 二叉搜索树 C++ 搜索操作总是给出 0;

标签 c++ binary-search-tree

在此 BST 中,searchbst 函数正在完美搜索,但此函数始终返回 0。它没有像我编程那样给出 5 或 8,所以代码中的错误是什么,因为这个问题存在

#include<iostream>
using namespace std;

struct bstnode{
bstnode *lchild;
int data;
bstnode *rchild;    
};

void creatbst(bstnode *&T,int k){
    if(T=='\0'){
        T=new(bstnode);
        T->data=k;
        T->lchild='\0';
        T->rchild='\0';
    }
    else if(k<T->data){
        creatbst(T->lchild,k);
    }
    else if(k>T->data){
        creatbst(T->rchild,k);
    }
}

int searchbst(bstnode *T,int k){
    if(T=='\0')
    return 5;
    else{

     if(k<T->data)
    searchbst(T->lchild,k); 

    else if(k>T->data)
    searchbst(T->rchild,k); 

    else
        return 8;
    }
}

int main(){
    bstnode *T;
    T='\0';
    creatbst(T,36);
    creatbst(T,20);
    creatbst(T,75);
    creatbst(T,42);
    creatbst(T,8);
    creatbst(T,31);
    creatbst(T,25);
    creatbst(T,3);
    creatbst(T,80);

    cout<<endl<<"searching for ";
    cout<<searchbst(T,3);
    cout<<endl<<"searching for ";
    cout<<searchbst(T,1);
    return 0;

}

最佳答案

您没有使用递归调用的返回值。

替换:

if(k<T->data)
  searchbst(T->lchild,k); 
else if(k>T->data)
  searchbst(T->rchild,k); 
else
  return 8;

与:

if(k < T->data)
  return searchbst(T->lchild, k);
else if(k > T->data)
  return searchbst(T->rchild, k);
else
  return 8;

关于c++ - 二叉搜索树 C++ 搜索操作总是给出 0;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18445428/

相关文章:

c++ - 在关闭套接字之前发送数据包

c++ - 在 boost::unordered_multimap 中循环遍历 equal_range

c++ - BST 递归解决方案中的第 K 个最小元素

java - 打印 Java 二叉搜索树

c++ - 在头文件中执行 const std::string 的正确方法?

c++ - 被删除的构造函数 "accessible"吗?

c++ - 指针运算 : out of bound without dereferencing

data-structures - 使用二叉搜索树(拉伸(stretch)树)实现 Rope 数据结构

java - 这个中序遍历算法是如何工作的?

algorithm - 是否有解决 `size` 或 `height` 的二叉树问题的技巧?