Balanced Binary Tree Insertion


First look at the insertion of the
binary search tree and the adjustment of the
balanced binary tree. The insertion of the balanced binary tree is a combination of the two.
Attention! ! ! When adjusting the height, you cannot directly add 1 to the maximum value of the height of the left subtree and the height of the right subtree, because the subtree may be an empty tree without the height variable, and an error will occur. There may be left empty, right empty, all empty, so troublesome. You can define a GetHeight function to find the height of the tree, and also deal with empty trees

#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

Guess you like

Origin blog.csdn.net/m0_54621932/article/details/114152976