平衡二叉树的插入

先看一下
二叉搜索树的插入
平衡二叉树的调整
平衡二叉树的插入是二者的综合
注意!!!调整高度时,不能直接是左子树高度和右子树高度中的最大值加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

猜你喜欢

转载自blog.csdn.net/m0_54621932/article/details/114152976