平衡二叉树(AVL)的插入和删除详解(上):http://blog.csdn.net/sysu_arui/article/details/7897017
1、测试代码
为减小篇幅,只给出了主程序,其他函数模块请看(上)中的描述。
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
AVL t ;
initAVL(t);
bool taller = false;
bool shorter = false;
int key;
string major;
ElementType e;
int choice = -1;
bool flag = true;
while(flag)
{
cout<<"--------------------"<<endl;
cout<<"0. print"<<endl
<<"1. insert"<<endl
<<"2. delete"<<endl
<<"3. search"<<endl
<<"4. exit"<<endl
<<"--------------------"<<endl
<<"please input your choice: ";
cin>>choice;
switch(choice)
{
case 0:
printAVL(t);
cout<<endl<<endl;
break;
case 1:
inOrderTraverse(t);
cout<<endl<<"input the elements to be inserted,end by 0:"<<endl;
while(cin>>key && key)
{
cin>>major;
ElementType e(key,major);
if(insertAVL(t,e,taller))
{
cout<<"insert element "<<e<<" successfully"<<endl;
}
else
{
cout<<"there already exists an element with key "<< e.key<<endl;
}
}
//while(cin>>e && e.key)
// {
// if(insertAVL(t,e,taller))
// {
// cout<<"insert element "<<e<<" successfully"<<endl;
// }
// else
// {
// cout<<"there already exists an element with key "<< e.key<<endl;
// }
// }
cout<<"after insert: "<<endl;
printAVL(t);
cout<<endl<<endl;
break;
case 2:
inOrderTraverse(t);
cout<<endl<<"input the keys to be deleted,end by 0:"<<endl;
while(cin>>key && key)
{
if(deleteAVL(t,key,shorter))
{
cout<<"delete the element with key "<<key<<" successfully"<<endl;
}
else
{
cout<<"no such an element with key "<<key<<endl;
}
}
cout<<"after delete: "<<endl;
printAVL(t);
cout<<endl<<endl;
break;
case 3:
inOrderTraverse(t);
cout<<endl<<"input the keys to be searched,end by 0:"<<endl;
while(cin>>key && key)
{
if(searchAVL(t,key))
cout<<key<<" is in the tree"<<endl;
else
cout<<key<<" is not in the tree"<<endl;
}
cout<<endl<<endl;
break;
case 4:
flag = false;
break;
default:
cout<<"error! watch and input again!"<<endl<<endl;
}
}
destroyAVL(t);
system("PAUSE");
return EXIT_SUCCESS;
}
注:
(1)前面我们对元素类型输入和输出操作符进行了重载,这里可以直接输入和输出。当然也可以采用先获取数据成员,然后构造对象的方式。
(2)请注意上面代码的I/O格式,下面的测试用例会给出示例。我们假设没有关键字为0,即采用0作为输入结束。
2、测试用例
(1) 输入1,开始insert。接着输入要插入的数据元素,每行一个(学号和专业之间以空格分隔),如果采用的是重载>>后的输入方式,那么以 0 0作为结束,如果采用的是另外的方式,直接输入0结束,上面的代码插入删除查找都是以0作为输入结束。
20 dm
10 english
5 physics
30 chinese
40 language
15 japanese
25 biology
23 mathematics
50 chemistry
1 physics
3 geography
0
插入完成后,会给出提示,最后给出前序和中序输出。可以对比下面的图看是否正确。
(2) 输入3,进行search。依次输入1 2 3 5 7 8 10 13 15 17 20 23 30 31 50 60 0
观察输出结果看是否正确
(3) 输入2,进行delete。依次输入15 23 25 1 30 50 40 3 0
(4) 输入1,打印平衡二叉树。比较看看输出和自己画的是否相符。
3、插入删除图例
(1)依次插入20、10、5、30、40、15、25、23、50、1、3
(2)在上图中依次删除15、23、25、1、30、50、40、3