균형 잡힌 이진 트리 삽입


먼저
이진 검색 트리의 삽입과
균형 이진 트리 의 조정을 살펴 봅니다 . 균형 이진 트리의 삽입은이 둘의 조합입니다.
주의! ! ! 높이를 조정할 때 왼쪽 하위 트리의 높이와 오른쪽 하위 트리의 높이의 최대 값에 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