1066 Root of AVL Tree(构建AVL树模板)

1066 Root of AVL Tree(构建AVL树模板)

在这里插入图片描述
在这里插入图片描述
构建AVL树

#include <iostream>
#include <string>
#include<algorithm>
#include<stack>
#include<string.h>
using namespace std;

typedef int ElementType;
typedef struct TNode* Position;
typedef Position BinTree;
struct TNode {
	ElementType Data;
	BinTree Left;
	BinTree Right;
};

BinTree NewNode(ElementType X)
{
	BinTree tmp = (BinTree)malloc(sizeof(struct TNode));
	tmp->Data = X;
	tmp->Left = tmp->Right = NULL;
	return tmp;
}

BinTree RR(BinTree root)
{//右右型
	BinTree tmp = root->Right;
	root->Right = tmp->Left;
	tmp->Left = root;
	return tmp;
}

BinTree LL(BinTree root)
{//左左型
	BinTree tmp = root->Left;
	root->Left = tmp->Right;
	tmp->Right = root;
	return tmp;
}

BinTree LR(BinTree root)
{//左右型(从右至左矫正)
	root->Left = RR(root->Left);//变为LL
	return LL(root);
}

BinTree RL(BinTree root)
{//右左型
	root->Right = LL(root->Right);//变为RR
	return RR(root);
}

int get_heigth(BinTree root)
{//得到结点高度
	if (!root)
		return 0;
	return max(get_heigth(root->Left), get_heigth(root->Right)) + 1;
}

BinTree Insert(BinTree Root, ElementType X)
{
	if (!Root)
	{
		Root = NewNode(X);
	}
	else
		if (X < Root->Data)
		{
			Root->Left = Insert(Root->Left, X);
			if (get_heigth(Root->Left) - get_heigth(Root->Right) == 2)
				Root = X > Root->Left->Data ? LR(Root) : LL(Root);
		}
		else
		{
			Root->Right = Insert(Root->Right, X);
			if (get_heigth(Root->Left) - get_heigth(Root->Right) == -2)
			//右子树高,根据插入数值大小选择翻转函数
				Root = X < Root->Right->Data ? RL(Root) : RR(Root);
		}
	return Root;
}
		
int main()
{
	int N,L;
	int i,flag=0;
	ElementType X;
	BinTree AVL = NULL;
	cin >> N;
	for (i = 0; i < N; i++)
	{
		cin >> X;
		AVL = Insert(AVL, X);
	}
	cout << AVL->Data;
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值