Root of AVL Tree

本题考场avl树的四种旋转方法与树的深度的计算

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.

首先题目告诉了四种AVL的自平衡方法,figure1到figure4分别是LL旋转,RR旋转,RL旋转与LR旋转,这是AVL树的自平衡法则

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

Sample Input 1:

5
88 70 61 96 120

Sample Output 1:

70

Sample Input 2:

7
88 70 61 96 120 90 65

Sample Output 2:

88

思路:

在程序最开始,我们需要定义树的结构体:

typedef struct Treenode * Tree;
struct Treenode
{
   
	int v;//储存节点的值
	Tree left, right;//储存左树的位置与右树的位置
};

主程序尽量简单:

int main()
{
   
	int n;
	scanf("%d", &n);
	Tree T;
	T = maketree(n);//构建AVL树
	printf("%d\n",T->v);//输出该树的根节点
	return 0;
}

构建一颗AVL树的函数有以下几个:

Tree maketree(int n);//建立自平衡二叉树
Tree newnode(int v);//建立新节点
Tree insert(Tree T, int v);//向树中插入元素
int height(Tree T);//计算一个树的高度
Tree LLrotation(Tree T);//LL旋转,左单旋转
Tree LRrotation(Tree T);//LR旋转,左右双旋
Tree RRrotation(Tree T);//RR旋转,右单旋转
Tree RLrotation(Tree T);//RL旋转,右左双旋

其中建立树的函数时会调用两个函数:建立新节点函数与插入新元素函数,其中插入新元素的函数会调用建立新节点函数与递归调用自身,同时插入完节点后,需要根据高度函数计算该树目前是否自平衡,不平衡的话需要根据四种情况进行调整,建立树的函数如下:

Tree maketree(int n)
{
   
	int v;
	scanf("%d", &v);
	Tree T = newnode(v);//建立根节点
	for (int i = 1; i < n; i++)
	{
   
		scanf("%d", &v);
		T = insert(T,v);//首先插入形成新的二叉树;
	}
	return T;
}

Tree newnode(int v)
{
   
	Tree T = (Tree)malloc(sizeof(struct Treenode));
	T->v = v;
	T->left = T
  • 17
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值