A1066 Root of AVL Tree (25 分)(构建平衡二叉树)

本文介绍AVL树的构建过程及其自平衡特性。通过两个方法实现:一是构建平衡二叉树,详细展示了节点插入及旋转操作;二是直接求解中位数,适用于快速获取AVL树根节点值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题意:

给出N个正整数,将他们依次插入一颗初始为空的AVL树上,求插入后根结点的值

思路:

对于AVL树的操作,非常麻烦而且复杂,有标准步骤

但本题只是输出中位数,也可得到许多分数,如下为中位数代码

得分:17(有两个case不能通过)

方法一:建平衡二叉树

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;

struct node {
    int v, height;
    node *lchild, *rchild;
}*root;

node* newnode(int v) {
    node* Node = new node;
    Node->v = v;
    Node->height = 1;
    Node->lchild = Node->rchild = NULL;
    return Node;
}

int getHeight(node* root) {
    if(root == NULL) {
        return 0;
    }
    return root->height;
}

void updatahegiht(node* root) {
    root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}

int getbalancefac(node* root) {
    return getHeight(root->lchild) - getHeight(root->rchild);
}

//左旋
void L(node* &root) {
    node* temp = root->rchild;
    root->rchild = temp->lchild;
    temp->lchild = root;
    updatahegiht(root);
    updatahegiht(temp);
    root = temp;
}

//右旋
void R(node* &root) {
    node* temp = root->lchild;
    root->lchild = temp->rchild;
    temp->rchild = root;
    updatahegiht(root);
    updatahegiht(temp);
    root = temp;
}

void insert(node* &root, int v) {
    if(root == NULL) {
        root = newnode(v);
        return ;
    }
    if(v < root->v) {
        insert(root->lchild, v);
        updatahegiht(root);
        if(getbalancefac(root) == 2) {
            if(getbalancefac(root->lchild) == 1) {  //LL
                R(root);
            } else if(getbalancefac(root->lchild) == -1) {  //LR
                L(root->lchild);
                R(root);
            }
        }
    } else {
        insert(root->rchild, v);
        updatahegiht(root);
        if(getbalancefac(root) == -2) { 
            if(getbalancefac(root->rchild) == -1) {     //RR
                L(root);
            } else if(getbalancefac(root->rchild) == 1) {   //RL
                R(root->rchild);
                L(root);
            }
        }
    }
}

int main() {
    int n, v;
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
        scanf("%d", &v);
        insert(root, v);
    }
    printf("%d\n", root->v);
    return 0;
}

方法二:中位数 

得分:17(有两个case不能通过)

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 25;
int num[maxn];
int main(){
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++){
        scanf("%d", &num[i]);
    }
    sort(num, num + n);
    printf("%d", num[n / 2]);
    return 0;
}

 

<think>好的,我需要回答如何检查AVL树是否平衡的问题。首先,AVL树的平衡条件是每个节点的左右子树高度差不超过1。所以,检查平衡的方法应该围绕这一点展开。 我应该先回忆AVL树的定义。根据引用[4],AVL树要求每个节点的左右子树高度差的绝对值不超过1。这意味着算法需要遍历每个节点,计算左右子树的高度差,并确认是否满足这个条件。 接下来,具体的实现步骤可能包括递归遍历每个节点。对于每个节点,首先检查其左右子树的高度差是否超过1。如果超过,则树不平衡。同时,还需要递归检查左右子树是否各自平衡。 然后,我需要考虑如何计算节点的高度。高度计算通常也是递归的,节点的高度等于其左右子树高度的最大值加1。这样,在遍历时,可以同时计算高度和检查平衡。 需要注意的是,递归过程中可能会出现重复计算高度的问题,但在这个检查平衡的场景下,可能可以接受,因为主要目的是验证整个树是否平衡,而不是优化性能。不过,如果树很大,可能需要优化,比如将高度缓存起来,不过根据引用的资料,AVL树的实现通常已经维护了平衡因子,所以或许可以直接使用节点的平衡因子进行检查。但引用[1]提到AVL节点包含平衡因子,所以检查时可以直接比较平衡因子是否在-1到1之间,而不必每次都重新计算高度。不过,用户的问题可能更偏向于如何从零开始检查一个给定的树是否是平衡的,而不依赖节点中存储的平衡因子,因此可能需要手动计算高度。 接下来,我需要组织步骤:首先,递归检查每个节点的左右子树高度差是否<=1,同时递归检查左右子树是否也满足这个条件。如果所有节点都满足,则树平衡。否则,不平衡。 然后,代码实现方面,可能需要一个辅助函数来计算节点的高度,另一个函数来递归检查每个节点是否满足平衡条件。例如,在Python中,可以定义两个函数:height(node)返回节点的高度,is_balanced(node)检查该节点是否平衡,并递归检查左右子树。 可能的边界情况是空树,此时高度为0,且视为平衡。如果某个节点的左右子树高度差为2,则立即返回不平衡。 现在,结合引用的资料,引用[4]提到插入或删除后需要旋转维护平衡,所以检查是否平衡应该在每次插入或删除后进行,但用户的问题是独立检查现有树是否平衡的方法。 最后,我需要确保回答的结构清晰,步骤说明算法,给出代码示例,并回答相关问题。同时,引用相关的引用来源,比如引用[4]提到的平衡条件。</think>### 如何检查AVL树是否平衡 AVL树的平衡性检查需满足以下条件:**每个节点的左右子树高度差绝对值不超过1**,且左右子树本身也是平衡的[^4]。实现算法需递归遍历所有节点,同时验证高度差和子树平衡性。 --- #### 检查算法步骤 1. **计算子树高度** - 空节点高度为$-1$或$0$(根据实现定义) - 非空节点高度为$1 + \max(左子树高度, 右子树高度)$ 2. **递归验证平衡性** - 若当前节点为空,视为平衡 - 计算左右子树高度差$\Delta h = |h_{left} - h_{right}|$ - 若$\Delta h > 1$,则树不平衡 - 递归检查左子树和右子树是否均平衡 --- #### Python实现代码 ```python class AVLNode: def __init__(self, key): self.key = key self.left = None self.right = None self.height = 0 # 节点高度 def is_avl_balanced(root): def check_balance(node): if not node: return True, -1 # 空节点高度为-1 # 递归检查左右子树 left_balanced, left_height = check_balance(node.left) right_balanced, right_height = check_balance(node.right) # 更新当前节点高度 current_height = 1 + max(left_height, right_height) # 检查高度差 if abs(left_height - right_height) > 1: return False, current_height # 返回当前子树是否平衡及高度 return (left_balanced and right_balanced), current_height balanced, _ = check_balance(root) return balanced ``` --- #### 关键逻辑说明 1. **高度计算**:通过后序遍历获取子树高度,避免重复计算[^1]。 2. **平衡判断**:若任意节点的左右子树高度差超过1,或子树不平衡,则整体不平衡。 3. **时间复杂度**:$O(n)$,需遍历所有节点。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值