先看一下
二叉搜索樹的插入
平衡二叉樹的調整
平衡二叉樹的插入是二者的綜合
注意!!!調整高度時,不能直接是左子樹高度和右子樹高度中的最大值加1,因為可能子樹為空樹,其沒有高度這個變數,會發生錯誤,可能有左空,右空,都空,好麻煩,可以定義一個GetHeight函式求樹高,對空樹也處理
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct AVLNode* AVLTree;
typedef int ElementType;
struct AVLNode {
ElementType data;
AVLTree left;
AVLTree right;
int height;
};
int GetHeight(AVLTree bt)
{
if(bt)
return max(GetHeight(bt->left),GetHeight(bt->right))+1;
return 0;
}
AVLTree LeftRotation(AVLTree a)
{
AVLTree b=a->left;
a->left=b->right;
b->right=a;
a->height=max(GetHeight(a->left),GetHeight(a->right))+1;
b->height=max(GetHeight(b->left),a->height)+1;
return b;
}
AVLTree RightRotation(AVLTree a)
{
AVLTree b=a->right;
a->right=b->left;
b->left=a;
a->height=max(GetHeight(a->left),GetHeight(a->right))+1;
b->height=max(a->height,GetHeight(b->right))+1;
return b;
}
AVLTree LeftRightRotation(AVLTree a)
{
a->left=RightRotation(a->left);
return LeftRotation(a);
}
AVLTree RightLeftRotation(AVLTree a)
{
a->right=LeftRotation(a->right);
return RightRotation(a);
}
AVLTree Insert(AVLTree t, ElementType x)
{
if (!t)
{
t = (AVLTree)malloc(sizeof(AVLNode));
t->data = x;
t->height = 0;
t->left = t->right = NULL;
}
else if (x < t->data) //插入左子樹
{
t->left = Insert(t->left, x);
if(GetHeight(t->left)-GetHeight(t->right)==2)
{
if (x < t->left->data) //LL
t = LeftRotation(t);
else //LR
//此處寫 else if (x > t->right->data) 提示可能是陣列越界,堆疊溢位(比如,遞回呼叫層數太多)等情況引起
//沒搞懂
t = LeftRightRotation(t);
}
}
else if (x > t->data) //插入右子樹
{
t->right = Insert(t->right, x);
if(GetHeight(t->right)-GetHeight(t->left)==2)
{
if (x < t->right->data) //Rl
t = RightLeftRotation(t);
else //RR
t = RightRotation(t);
}
}
//相等都不用管
t->height=max(GetHeight(t->left),GetHeight(t->right))+1;
return t;
}
//如果一棵樹是從頭開始建,注意初始化為NULL
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/264553.html
標籤:其他
