1066. Root of AVL Tree (25)

好久没写博客了,更新一波

这个是课本上的东西,一模一样,就是树的形式变换要记一下,没那个示意图估计是写不出来了

还有就是之前碰到二叉树建树的问题发现课本没有建二叉树的程序,其实就是这个题目,二叉树怎么都可以建出来,只是不一定是avl树(最坏是一条链)

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 21;
int n, a[maxn];
typedef struct Node * List;
struct Node {
	int key;
	List Right, Left;
};
List Newnode(int key)
{
	List node = new Node;
	node->key = key;
	node->Right = node->Left = NULL;
	return node;
}
int GetH(List root)
{
	if (root == NULL)return 0;
	else
	{
		int lh = GetH(root->Left);
		int rh = GetH(root->Right);
		return max(lh, rh) + 1;
	}
}
List SingleRightR(List root)
{
	List B = root->Right;
	root->Right = B->Left;
	B->Left = root;
	return B;
}
List SingleLeftR(List root)
{
	List B = root->Left;
	root->Left = B->Right;
	B->Right = root;
	return B;
}
List DoubleRightLeftR(List A)
{
	A->Right = SingleLeftR(A->Right);
	return SingleRightR(A);
}

List DoubleLeftRightR(List A)
{
	A->Left = SingleRightR(A->Left);
	return SingleLeftR(A);
}
List Insert(List root, int key)
{
	if (root == NULL)root = Newnode(key);
	if (key > root->key)
	{
		root->Right = Insert(root->Right, key);
		if (GetH(root->Right) - GetH(root->Left) == 2)
		{
			if (key > root->Right->key)root = SingleRightR(root);
			else root = DoubleRightLeftR(root);
		}
	}
	if (key < root->key)
	{
		root->Left = Insert(root->Left, key);
		if (GetH(root->Left) - GetH(root->Right) == 2)
		{
			if (key < root->Left->key)root = SingleLeftR(root);
			else root = DoubleLeftRightR(root);
		}
	}
	return root;
}
int main()
{
	scanf("%d", &n);
	for (int i = 0; i < n; i++)scanf("%d", &a[i]);
	List root = NULL;
	for (int i = 0; i<n; i++)
	{
		root = Insert(root, a[i]);
	}
	printf("%d\n", root->key);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值