binary search tree - BST insertion with C++ -
i created function insert data bst , works fine. used "pass reference" , value of "head" supposed change after each insertion. however, found "head" pointing first value inserted. here explain causes "head" point first data inserted?
void insert(node *&head, int val){ if(head == null){ head = newnode(val); } else{ if(val <head->data) insert(head->left,val); else insert(head->right,val); } }
that how function should work, head
should never change or lose track of tree root.
as long have head
pointing @ root, have access whole tree.
the reason why value not changing is, when writing insert(head->left,val);
you not assigning new value head
, passing reference left child next function call.
Comments
Post a Comment