数据结构实验之查找二:平衡二叉树

来源:互联网 发布:使命召唤emp知乎 编辑:程序博客网 时间:2024/06/04 18:42

Problem Description

根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。

Input

输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。

Output

输出平衡二叉树的树根。

Example Input

588 70 61 96 120

Example Output

70
#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct tree{    int data;    struct tree *lc, *rc;    int height;} BiTree;int Deep(BiTree *T)      //返回树的深度{    if(T == NULL)        return -1;    return T->height;}int Max(int x, int y){    return x>y?x:y;}BiTree *LLRotate(BiTree *p){    BiTree *p1;    p1 = p->lc;    p->lc = p1->rc;    p1->rc = p;    p->height = Max(Deep(p->lc), Deep(p->rc)) + 1;    p1->height = Max(Deep(p1->lc), p->height) + 1;    return p1;}BiTree *RRRotate(BiTree *p){    BiTree *p1;    p1 = p->rc;    p->rc = p1->lc;    p1->lc = p;    p->height = Max(Deep(p->lc), Deep(p->rc)) + 1;    p1->height = Max(Deep(p1->rc), p->height) + 1;    return p1;}BiTree *LRRotate(BiTree *p){    p->lc = RRRotate(p->lc);    return LLRotate(p);}BiTree *RLRotate(BiTree *p){    p->rc = LLRotate(p->rc);    return RRRotate(p);}BiTree *Insert(BiTree *T, int x){    if(T == NULL)        //T是空树则开辟一个新节点    {        T = (BiTree*)malloc(sizeof(BiTree));        T->data = x;        T->lc = NULL;        T->rc = NULL;        T->height = 0;    }    else    {        if(T->data > x)   //T的data值大于插入的数值,将x插到T的左子树上        {            T->lc = Insert(T->lc, x);  //递归调用            if(Deep(T->lc) - Deep(T->rc) == 2)  //出现不平衡            {                if(T->lc->data > x)   //如果插到了左子树的左子树上                    T = LLRotate(T);                else                    T = LRRotate(T);            }        }        else   //T的data值小于插入的数值,将x插到T的右子树上        {            T->rc  = Insert(T->rc, x);            if(Deep(T->rc) - Deep(T->lc) == 2)            {                if(T->rc->data < x)   //插到了右子树的右子树上                    T = RRRotate(T);                else                    T = RLRotate(T);            }        }    }    T->height = Max(Deep(T->lc), Deep(T->rc)) + 1;    return T;}int main(){    int n, x;    BiTree *T;    T = NULL;    scanf("%d", &n);    while(n--)    {        scanf("%d", &x);        T = Insert(T, x);    }    printf("%d\n", T->data);    return 0;}



阅读全文
0 0
原创粉丝点击