数据结构实验之查找二:平衡二叉树
Time Limit: 400MS
Memory Limit: 65536KB
Problem Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Example Input
5 88 70 61 96 120
Example Output
70#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct node { int data; struct node *lc,*rc; int bf; }Bitree; int max1(int a,int b) { return (a>b?a:b); } int deep(Bitree* tree) { if(!tree) { return -1; } else { return tree->bf; } } Bitree* L_Rotate(Bitree* root) //左旋 { Bitree *p; p = root->rc; root->rc = p->lc; p->lc = root; p->bf = max1(deep(p->lc),deep(p->rc)) + 1; root->bf = max1(deep(root->lc),deep(root->rc)) + 1; return p; } Bitree* R_Rotate(Bitree* root) //右旋 { Bitree *p; p = root->lc; root->lc = p->rc; p->rc = root; p->bf = max1(deep(p->lc),deep(p->rc)) + 1; root->bf = max1(deep(root->lc),deep(root->rc)) + 1; return p; } Bitree* L_R_Rotate(Bitree* root) //先左旋再右旋 { root->lc = L_Rotate(root->lc); root = R_Rotate(root); return root; } Bitree* R_L_Rotate(Bitree* root) //先右旋再左旋 { root->rc = R_Rotate(root->rc); root = L_Rotate(root); return root; } Bitree* create(Bitree* root,int k) { if(!root) { root = (Bitree *)malloc(sizeof(Bitree)); root->data = k; root->rc = root->lc = NULL; root->bf = 0; } else { if(k < root->data) { root->lc = create(root->lc,k); if(deep(root->lc)-deep(root->rc) > 1) { if(k < root->lc->data) { root = R_Rotate(root); } else { root = L_R_Rotate(root); } } } else if(k > root->data) { root->rc = create(root->rc,k); if(deep(root->rc)-deep(root->lc) > 1) { if(k < root->rc->data) { root = R_L_Rotate(root); } else { root = L_Rotate(root); } } } } root->bf = max1(deep(root->lc),deep(root->rc)) + 1; return root; } int main() { int n; int k; Bitree * root = NULL; scanf("%d",&n); while(n--) { scanf("%d",&k); root = create(root,k); } printf("%d\n",root->data); return 0; }