c++ - Traversing a binary search tree -


i've implmented basic binary search tree. here's node

 #ifndef node_h     #define node_h      template<typename t> class node{          template<typename e> friend class bst;          public:             node():data(0), left(null), right(null){}             node(t data):data(data),left(null), right(null){}             private:             t data;             node<t>* left;             node<t>* right;     };  #endif 

and here's bst.

#ifndef bst_h #define bst_h  template<typename t> class bst{     public:         bst():root(null), nodes(0){}         bst(node<t>* root):root(root), nodes(0){}          void insert(node<t>* root, const t& data){              if(root == null){                 node<t>* root = new node<t>();                 root->data = data;                 nodes++;                 return;             }else if(data <= root->data) {                 insert(root->left, data);              }else if(data >= root->data){                 insert(root->right, data);              }         }          void preorder(node<t>* root){             if(root == null) return;             std::cout<< root->data<<'\n';              preorder(root->left);             preorder(root->right);         }     private:         node<t>* root;         int nodes; }; #endif 

here's calling function

int main(){      node<int>* root = new node<int>(17);     bst<int>* t = new bst<int>(root);       t->insert(root,21);     t->insert(root,12);     t->insert(root, 9);      t->preorder(root);      delete t; } 

the output 17, root. feel somehow insert method hasn't worked right, since preorder pretty standard implementation. can me going wrong here.

i see 2 problems.

the first declaring root local variable inside insert() method. name overlaps data member root.

the second that, have designed it, root not updated.

this code should work:

void insert(node<t>*& root, // <-- root reference updating             const t& data){          if(root == null){             root = new node<t>(); // <-- here update root             root->data = data;             nodes++;             return;         }else if(data <= root->data) {             insert(root->left, data);          }else if(data >= root->data){             insert(root->right, data);          }     } 

of course, refactor , more concise , elegant implementation. should produce result expect


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -