zoukankan      html  css  js  c++  java
  • 75 平衡二叉树的根(25 分)

    将给定的一系列数字插入初始为空的AVL树,请你输出最后生成的AVL树的根结点的值。

    输入格式:

    输入的第一行给出一个正整数N(≤),随后一行给出N个不同的整数,其间以空格分隔。

    输出格式:

    在一行中输出顺序插入上述整数到一棵初始为空的AVL树后,该树的根结点的值。

    输入样例1:

    5
    88 70 61 96 120
    

    输出样例1:

    70
    

    输入样例2:

    7
    88 70 61 96 120 90 65
    

    输出样例2:

    88



    代码



    #include <stdio.h>
    #include <stdlib.h>
    struct node{
    int data,shen;
    struct node*l,*r;
    };
    int max(int a,int b){
    return a>b?a:b;
    }
    int shendu(struct node*p){
    if (p==NULL){
    return -1;
    }
    return p->shen;
    }
    struct node *zuozuo(struct node*p){
    struct node*q;
    q=p->l;
    p->l=q->r;
    q->r=p;
    q->shen=max(shendu(q->l),p->shen)+1;
    p->shen=max(shendu(p->l),shendu(p->r))+1;
    return q;
    }
    struct node *youyou(struct node *p){
    struct node *q;
    q=p->r;
    p->r=q->l;
    q->l=p;
    q->shen=max(shendu(q->r),p->shen)+1;
    p->shen=max(shendu(p->l),shendu(p->r))+1;
    return q;
    }
    struct node *zuoyou(struct node*p){
    p->l=youyou(p->l);
    return zuozuo(p);
    }
    struct node *youzuo(struct node*p){
    p->r=zuozuo(p->r);
    return youyou(p);
    }
    struct node *creat(struct node*p,int n){
    if (p==NULL){
    p=(struct node*)malloc(sizeof(struct node));
    p->l=NULL;
    p->r=NULL;
    p->data=n;
    p->shen=0;
    }
    else if (n<p->data){
    p->l=creat(p->l,n);
    if (shendu(p->l)-shendu(p->r)>1){
    if (n<p->l->data){
    p=zuozuo(p);
    }
    else{
    p=zuoyou(p);
    }
    }
    }
    else if (n>p->data){
    p->r=creat(p->r,n);
    if (shendu(p->r)-shendu(p->l)>1){
    if (n>p->r->data){
    p=youyou(p);
    }
    else{
    p=youzuo(p);
    }
    }
    }
    p->shen=max(shendu(p->l),shendu(p->r))+1;
    return p;
    }
    int main(){
    int n,m;
    scanf("%d",&n);
    struct node*p=NULL;
    for (int i=0;i<n;i++){
    scanf("%d",&m);
    p=creat(p,m);
    }
    printf("%d\n",p->data);
    return 0;
    }

  • 相关阅读:
    [问题2014A13] 解答
    [问题2014A12] 解答
    [问题2014A13] 复旦高等代数 I(14级)每周一题(第十五教学周)
    [问题2014A10] 解答
    php使用amqplib方式使用rabbitmq
    Ubuntu 16.04 源码编译安装PHP7+swoole
    Ubuntu apt-get更换阿里云源
    微信企业号网页授权
    nginx转发swoole以及nginx负载
    PHP 命名空间
  • 原文地址:https://www.cnblogs.com/linguiquan/p/8934029.html
Copyright © 2011-2022 走看看