binary search tree c++ searching operation always giving 0; -
in bst,the searchbst function searching function returning 0 always. not giving 5 or 8 have programmed error in code because of problem there
#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 "; cout<<searchbst(t,3); cout<<endl<<"searching "; cout<<searchbst(t,1); return 0; }
your code has undefined behavior: if don't follow conditions leading return 5;
or return 8;
statements, call searchbst()
, ignore result, , fall of function. meant return result of searchbst()
:
return searchbst(t->rchild, k);
btw, have funny way of writing null pointer constant: although '\0'
works, conventional way use 0
or nullptr
(the latter c++11 way).
Comments
Post a Comment