平衡二叉树(AVL树)
一、平衡二叉树的概念 请看链接:http://baike.baidu.com/view/593144.htm
二、平衡二叉树的算法逻辑 请看链接:http://sjjg.js.zwu.edu.cn/SFXX/chazhao/chazhao7.3.2.html
实现代码如下:
if (root->data == data)
{
return &root->data;
}
else if (data < root->data)
{
return search(root->lchild, data);
}
else
{
return search(root->rchild, data);
}
}
/*
函数名:void print(BSTree & root, char * format);
功能:输出平衡二叉树中的所有的元素(小->大,中序遍历)
参数:
输入:
root (BSTree &): 平衡二叉树的根
format (char *): 元素输出的格式
输出:无
返回值:无
*/
void print(BSTree & root, char * format)
{
if (NULL == root)
{
return ;
}
print(root->lchild, format);
printf(format, root->data);
print(root->rchild, format);
}
/*
函数名:void clear(BSTree & root);
功能:释放平衡二叉树的空间
参数:
输入:
root (BSTree &): 平衡二叉树的根
输出:无
返回值:无
*/
void clear(BSTree & root)
{
if (NULL == root)
{
return ;
}
clear(root->lchild);
clear(root->rchild);
free(root);
}
int main()
{
BSTree root = NULL;
bool taller = false;
srand(time(NULL));
int tmp;
for (int i = 0; i < 10; ++i)
{
tmp = rand() % 16;
bool flag = insert(root, tmp, taller);
if (flag)
{
printf("%d insert success!/n", tmp);
}
else
{
printf("%d insert failure!/n", tmp);
}
}
cout << "insert done" << endl;
print(root, "%d ");
cout << endl;
for (int i = 0; i < 5; ++i)
{
tmp = rand() % 16;
type * p = search(root, tmp);
if (NULL == p)
{
printf("not found %d!/n", tmp);
}
else
{
printf("found %d!/n", *p);
}
}
clear(root);
cout << "clear done" << endl;
return 0;
}
运行结果如下: