c++ - how to delete a Node in binary tree -
the program simple following step:
- find min value of binary tree;
- record min value in vector;
- delete node min value in tree;
- repeat 1-3 till tree empty.
no error reported when run, function removenode keep printf("remove bug1!\n");
can not find logical mistake, not understand why happens. structure of function is:
- 'if min=key`,found it,call function removerootmatch
- else if
min<root->key
, 'left not null`,go left - else print
bug
the tree defined following, language c++
typedef struct mynode* lpnode; typedef struct mynode node; struct mynode { double key; lpnode left; //left subtree lpnode right; //right subtree };
main part of program following:
- nmax initialed 0,
- sortedvector alloacted vector space large total nodes in tree,
- min initialed 99999.
- minvalue return min value of tree.
comparedouble(a,b) return 1
if < b
,return 2if > b
,return 3 if equal//remove root void removerootmatch(lpnode root) { lpnode tmp = makenewnode(root->key); tmp->left = root->left; tmp->right = root->right; //no child if(root->left==null && root->right == null) { root = null; delete root;
} else if(root->left==null && root->right!=null){ //one right child root = root->right; tmp->right = null; delete tmp;
} else { printf("remove root bug!\n"); } }//remove node void removematch(lpnode root,lpnode match,bool left) { //no child if(match->left==null && match->right == null){ left==true? root->left=null: root->right=null; delete match; } else if(match->left==null && match->right!=null){//one right child left==true? root->left=match->right: root->right=match->right; delete match; } else { printf("remove root bug!\n"); } } //delete node void removenode(lpnode root,double min) { if(comparedouble(min,root->key)==3){ removerootmatch(root); }else if(comparedouble(min,root->key)==1 && root->left != null) { comparedouble(min,root->key)==3 ? removematch(root,root->left,true): removenode(root->left,min); }else{ printf("remove bug1!\n"); } }
this function call removenode function.
//call minvalue find min key //record min key in vector //call removenode delete node //repeat till tree empty void problem1(lpnode root,double* sortedvector,int& nmax) { double min = max; while(root!=null) { sortedvector[nmax] = minvalue(root,min) ; nmax++; removenode(root,min); } printf("the tree empty"); }
sortedvector[nmax] = minvalue(root,min) ; removenode(root,sortedvector[nmax]);//change here nmax++;
you have problem pass min. here answer, not read title , vote.
Comments
Post a Comment