PTA-04-树5 Root of AVL Tree

这是一篇关于PTA中AVL树的题目,主要涉及AVL树的性质和平衡旋转规则,包括左旋(RR, LL)和右旋(LR, RL)。通过给出的插入序列,需要计算并输出最终AVL树的根节点值。" 111916722,10296967,ELK集群性能优化实践:日志采集与处理效率提升,"['ELK', '日志处理', '性能调优', 'Elasticsearch集群']
摘要由CSDN通过智能技术生成

题目描述

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.
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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


解答

AVL旋转:
向左旋 RR:左旋拎右 右的左儿子挂根
向右旋 LL:右旋拎左 左的右儿子挂根
LR:根节点的左儿子RR 再LL
RL:根节点的右儿子LL 再RR

思路:
构建平衡二叉树
弄明白插入的原理建树就很轻松了

AVL旋转的讲解

#include<iostream>
#include<stdlib.h>
using namespace std;

typedef struct AvlNode *Tree;
struct AvlNode{
   
    int data;
    Tree Lchild;
    Tree Rchild;
    int height;//记录结点的高度 方便旋转
};

int Max(int a,int b)
{
   
     return (a>b?a:b);
}
int height(Tree T)
{
   
    if(!T) return -1;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值