平衡二叉树

来源:互联网 发布:框架图制作软件 编辑:程序博客网 时间:2024/05/16 13:51

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

Time Limit: 400MS Memory limit: 65536K

题目描述

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

输入

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

输出

输出平衡二叉树的树根。

示例输入

588 70 61 96 120

示例输出

70

提示

 

来源

看了下网上的二叉树代码,感觉在RL和LR型插入的时候旋转的有错误,所以自己做了下改动!
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<malloc.h>struct node{    int data;    int hight;    struct node *lc,*rc;};int max(int x,int y){    if(x>y)    {         return x;    }    else    {        return y;    }}//二叉树高度int depth(struct node *root){    if(root==NULL)    {        return -1;    }    else    {        return root->hight;    }}//左子树的左子树节点插入,则进行右旋转(左左-->右转)struct node *LL(struct node *root){    struct node *tail;    tail=root->lc;    root->lc=tail->rc;    tail->rc=root;    root->hight=max(depth(root->lc),depth(root->rc))+1;    return tail;};//右子树的右子树节点插入,则进行左旋转(右右-->左转)struct node *RR(struct node *root){    struct node *tail;    tail=root->rc;    root->rc=tail->lc;    tail->lc=root;    root->hight=max(depth(root->lc),depth(root->rc))+1;    return tail;};//左子树的右子树节点插入,则先进行左旋转,再进行右旋转struct node *LR(struct node *root){    root->lc=RR(root->lc);    return LL(root);};//右子树的左子树节点插入,则先进行右旋转,再进行左旋转struct node *RL(struct node *root){    root->rc=LL(root->rc);    return RR(root);};//创建二叉树的过程struct node *creat(struct node *root,int e){    if(root==NULL)    {        root=(struct node *)malloc(sizeof(struct node));        root->data=e;        root->lc=root->rc=NULL;        root->hight=0;    }    else if(root->data>e)    {        root->lc=creat(root->lc,e);        if((depth(root->lc)-depth(root->rc))>1)        {            if(root->lc->data>e)            {                root=LL(root);            }            else            {                root=LR(root);            }        }    }    else if(root->data<e)    {        root->rc=creat(root->rc,e);        if((depth(root->rc)-depth(root->lc))>1)        {            if(root->rc->data<e)            {                root=RR(root);            }            else            {                root=RL(root);            }        }    }    root->hight=max(depth(root->lc),depth(root->rc))+1;    return root;};int main(){    int n;    scanf("%d",&n);    int a[30];    struct node *root;    root=NULL;    for(int i=0;i<n;i++)    {        scanf("%d",&a[i]);        root=creat(root,a[i]);    }    printf("%d\n",root->data);    return 0;}


0 0
原创粉丝点击