之前已经写了二叉树的创建,插入与旋转,详见https://blog.csdn.net/weixin_42579072/article/details/102616919
pavlNode DeleteNode(pavlNode &root, int key)
{
if (key < root->key)
{
DeleteNode(root->lChild, key);
if (AvlTreeHeight(root->rChild) - AvlTreeHeight(root->lChild) == 2)
{//失去平衡,需要旋转
AvlNode *p = root->rChild;
if (AvlTreeHeight(p->lChild)>AvlTreeHeight(p->rChild))
root = RL(root);
else
root = RR(root);
}
}
else if (key > root->key)
{
DeleteNode(root->rChild, key);
if (AvlTreeHeight(root->lChild) - AvlTreeHeight(root->rChild) == 2)
{//失去平衡,需要旋转
AvlNode *p = root->lChild;
if (AvlTreeHeight(p->rChild) > AvlTreeHeight(p->lChild))
root = LR(root);
else
root = LL(root);
}
}
else
{
if (root->lChild&&root->rChild)//左右子树都存在
{
if (AvlTreeHeight(root->lChild) > AvlTreeHeight(root->rChild))
{
AvlNode *p = TreeNodePre(root->lChild);
root->key = p->key;
DeleteNode(root->lChild, p->key);
}
else
{
AvlNode *p = TreeNodePost(root->rChild);
root->key = p->key;
DeleteNode(root->rChild, p->key);
}
}
else
{
if (root->lChild)//只存在左子树
{
root->key = root->lChild->key;
root->lChild = nullptr;
}
else if (root->rChild)//只存在右子树
{
root->key = root->rChild->key;
root->rChild = nullptr;
}
else //叶子结点
root = nullptr;
}
}
return root;
}
别忘了在MyAVL.h中加入该函数声明。
main.cpp如下:
#include"MyAVL.h"
#include<iostream>
#define len 10
using namespace std;
int main()
{
int a[len] = { 3, 2, 1, 4, 5, 6, 7, 10, 9, 8 };
cout << "待插入元素为:";
for (int i = 0; i < len; i++)
{
cout << a[i] << " ";
}
cout << endl;
pavlNode root = NULL;
for (int i = 0; i < len; i++)
{
root = InsertNode(root,a[i]);
if (NULL == root)
cout << "插入" << a[i] << "失败" << endl;
}
cout << "中序遍历:";
InOrder(root);
cout << endl;
cout << "前序遍历:";
PreOrder(root);
cout << endl;
cout << "删除指定节点后:"<<endl;
root = DeleteNode(root, 7);
cout << "中序遍历:";
InOrder(root);
cout << endl;
cout << "前序遍历:";
PreOrder(root);
cout << endl;
TreeDestroy(root);
system("pause");
return 0;
}