Thursday, 15 July 2010

recursion - Recursive function for insertion in Binary Search Tree ( C++ ) -



recursion - Recursive function for insertion in Binary Search Tree ( C++ ) -

i trying insert new node bst using recursion. losing links after inserting. in-order traversal showed programme able access root node. here's program

class bst

class bst { struct node { struct node *lchild; int info; struct node *rchild; }*start; public: bst(); void insert(int num,struct node *start); void search(int num,struct node *start); void display(); void inorder(node *start); struct node *getroot(){ homecoming start; } };

insertion function

void bst :: insert(int num,struct node *ptr) { if(ptr == null) { ptr = new node; ptr->info = num; ptr->lchild = null; ptr->rchild = null; if(start == null) start = ptr; return; } else if(num < ptr->info) { insert(num,ptr->lchild); } else if(num > ptr->info) { insert(num,ptr->rchild); } else { cout << "duplicate element \n"; return; } }

main function

int main() { bst s; int option,key; cout << "enter element\n"; cin >> key; s.insert(key,s.getroot()); }

how can maintain proper links without changing homecoming type of insert function ?

is start initialized null somewhere?

also, when start not null, never link newly created node tree:

if(ptr == null) { ptr = new node; ptr->info = num; ptr->lchild = null; ptr->rchild = null; if(start == null) start = ptr; return; }

you should check if node's kid null , link new node in there. think taking recursion 1 level far.

c++ recursion data-structures binary-tree binary-search-tree

No comments:

Post a Comment