c++ - Root node in Binary search tree is null -
i learning c++ , data structures have implemented binary search tress can body tell issue in code getting root pointer null. unable create tree. final goal search key in tree. have written method it. unfortunately unable create tree. have tested writing traversal code.
#include <stdio.h> #include <conio.h> #include <iostream.h> // node structure struct treenode { int value; int key; struct treenode *left; struct treenode *right; treenode() { left=null; right=null; } }; void preorder (treenode *); void insertnode(treenode *, int, int); treenode* findnode(treenode *anode, int); void main() { treenode *root = null; for(int = 15; i<= 300; i+=15) { insertnode(root, i, i); if (root!=null) { cout<<root ->value<<endl; } } cout<<"the preorder traversal"<<endl; preorder(root); getch(); } void preorder (treenode *p) { if (p!=null) { cout<<p ->value<<endl; preorder(p ->left); preorder(p ->right); } else{ cout << "null"<<endl; } } void createnewnode(treenode *newnode, int avalue, int akey) { newnode = new treenode; // create new node newnode -> value = avalue; // set data newnode -> key = akey; // set key cout<<newnode ->value<<endl; // set left,right newnode -> left = newnode -> right = null; } void insertnode(treenode *anode, int avalue, int akey) { if (anode == null) { treenode *newnode = new treenode; // create new node newnode -> value = avalue; // set data newnode -> key = akey; // set key //createnewnode(newnode, avalue, akey); if(newnode == null) { cout<< "null returned"<<endl; } else { cout<< newnode -> key <<endl; } anode = newnode; } else if (akey == anode->key) { cout<<akey<<endl; return; } else if (akey < anode->key) { insertnode((anode->left), avalue, akey); } else { insertnode((anode->right), avalue, akey); } } treenode* findnode(treenode *anode, int akey) { if (anode == null) { return null; } else if (anode->key == akey) { return anode; } else if (akey <= anode->key) { return findnode(anode->left, akey); } else { return findnode(anode->right, akey); } }
the main problem according me in insert node code, passing anode
call value instead of call reference. instead of using treenode *anode
in insert node function, try using treenode * &anode
.
Comments
Post a Comment