void main() { int K[N] = {50,19,35,55,20,5,100,52,88,53,92}; //建一棵图5.11所示的树 BinarySearchTree<int> aBST; BinaryTreeNode<int > *newpointer, *node1, *node2; // 循环插入结点 for (int i = 0; i < N; i ++) { newpointer = new BinaryTreeNode<int>(); newpointer->setValue(K[i]); aBST.InsertNode(aBST.Root(), newpointer); //依次插入结点 if (K[i] == 52){ //记录待删除结点的指针node1 node1 = newpointer; // cout<<node1->value()<<endl; } if (K[i] == 55) //记录待删除结点的指针node2 node2 = newpointer; } // 遍历结点 cout << "中序周游二叉搜索树:" << endl; aBST.InOrder(aBST.Root()); cout << endl; // 删除两个结点 //教材中没讲这个算法 // cout << "删除结点52, 55." << endl; // BST.DeleteNode(node1); // aBST.DeleteNode(node2); // 删除两个结点的改进算法 cout << "删除结点52, 55." << endl; aBST.DeleteNodeEx(node1); aBST.DeleteNodeEx(node2); // 遍历节点 cout << "删除结点之后中序周游二叉搜索树:" << endl; aBST.InOrder(aBST.Root()); cout << endl; }
int main() { BinarySearchTree bst; bstNode* t = bst.Root(); hcnode *h = NULL; hcnode a, b, c; int g=0; int t1=1; cout<<"enter '.' "<<"to end input"<<endl; while(t1) { //loop for input values cout<<"Enter char: "; cin>>a.c; if(a.c=='.') break; cout<<"Enter freq: "; cin>>a.freq; a.left = NULL; a.right = NULL; bst.add(t,a); g++; } if(g==1) //if only one node is entered there is no traversal as why a code there is only one char; { cout<<"only one element "<<endl; exit(1); } while(!bst.check(t)) //check upon number of nodes and finally only one bstnode remains with the hcnode with all data { a = bst.minimum(t); //gets first minimum hcnode from bst bst.del(t,a); //deletes the mininmum node from bst as it is already accessed b = bst.minimum(t); //next min node bst.del(t,b); //del last node ie it is in hcnode b c = bst.minimum(t); //next min node bst.del(t,c); //del last node ie it is in hcnode c add(h,a,b,c); //adds the three nodes ie create a combined node bst.add(t,*h); //adds combined node to bst } int count=0; inorderc(t,count); //if count is two add function has only two hcnodes if(count==2) { if(t->lchild!=NULL) { add(h,t->data,t->lchild->data); //h=node;a=node with max freq;b=node with less freq(h,a,b) } if(t->rchild!=NULL) { add(h,t->rchild->data,t->data); } } hcnode*f=h; cout<<endl<<"printing level order "<<endl; levelorder(h); cout<<endl; string s; cout<<endl<<"Enter string: "; cin>>s; for(int i=0;i<s.length();i++) { if(s[i]=='1') { f = f->mid; } else if(s[i]=='0') { f = f->left; } else { f=f->right; } if(f->left==NULL && f->right==NULL&&f->mid==NULL) { cout<<f->c; f = h; } } return 0; }