/* recursive binary search tree code with functions to add,display, and search. */ //this program is compiled using devcpp (gcc) //the search function is not working correctly, the return value for // cout<<"return value: "<<search(root,23)<<endl; //is 89, Code: #include <cstdlib> #include <iostream> using namespace std; typedef struct node { int data; node *right; node *left; }treeNode; treeNode *root = NULL; treeNode *iter = root;//used to insert in the current node void insert(int nodeVal); bool search(node *temp,int searchVal); void display(node *temp); void display1(node *temp); void display2(node *temp); int main(int argc, char *argv[]) { insert(10); insert(14); insert(4); insert(7); insert(11); insert(13); insert(2); insert(10); int t= 123456; char c[20]; do { itoa(t,c,10); cout<<c<<endl; cout<<t%10<<endl; t=t/10; }while(t!=0); display(root);cout<<endl; display1(root);cout<<endl; display2(root);cout<<endl; //cout<<"return value: "<<search(root,23)<<endl;//this is printing as 89 why?? if(search(root,23)) cout<<"search(root,23) "<<"found"<<endl; else cout<<"23 not found"; //cout<<"return value: "<<search(root,13)<<endl; if(search(root,13)) cout<<"search(root,13) "<<"found"<<endl; else cout<<"13 not found"; system("PAUSE"); return EXIT_SUCCESS; } void insert(int nodeVal) { treeNode *node= new treeNode; node->data = nodeVal; node->left = NULL; node->right = NULL; iter = root; if(root == NULL) { root = node; } while(iter != NULL) { if(iter->data >= node->data)//insert in left { if(iter->left == NULL) { iter->left = node; break; } else iter = iter->left; } else if(iter->data < node->data)//insert in right { if(iter->right == NULL) { iter->right = node; break; } else iter = iter->right; } } } void display(node *temp) { if(temp == NULL) return; display(temp->left); cout<<temp->data<<'\t'; display(temp->right); } void display1(node *temp) { if(temp == NULL) return; display1(temp->left); display1(temp->right); cout<<temp->data<<'\t'; } void display2(node *temp) { if(temp == NULL) return; cout<<temp->data<<'\t'; display2(temp->left); display2(temp->right); } bool search(node *temp,int searchVal) { if(temp == NULL) { cout<<"temp is null "<<endl; return false; } cout<<"searching for "<<searchVal<<endl; if(searchVal == temp->data) { cout<<"temp->data is"<<temp->data<<endl; return true; } else { if(searchVal < temp->data) search(temp->left,searchVal); else search(temp->right,searchVal); } }