数据结构实验之查找二:平衡二叉树
Time Limit: 400 ms
Memory Limit: 65536 KiB
#include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int data; int high; struct node *lt, *rt; }; int max(int a, int b) { return a>b?a:b; } ///深度 int deep(struct node *root) { if(root==NULL) return -1; else return root->high; } struct node *LL(struct node *root) { struct node *p=root->lt; root->lt=p->rt; p->rt=root; root->high=max(deep(root->lt), deep(root->rt))+1; return p; } struct node *RR(struct node *root) { struct node *p=root->rt; root->rt=p->lt; p->lt=root; root->high=max(deep(root->lt), deep(root->rt))+1; return p; } struct node *RL(struct node *root) { root->rt=LL(root->rt); root=RR(root); return root; } struct node *LR(struct node *root) { root->lt=RR(root->lt); root=LL(root); return root; } struct node *Insert(struct node *root, int num) { if(!root) { root=(struct node *)malloc(sizeof(struct node)); root->data=num; root->high=0; root->lt=NULL; root->rt=NULL; } else { if(num<root->data)///数据比根小 { root->lt=Insert(root->lt, num);///加到左子树上 ///先判断是否要转 if(abs(deep(root->lt)-deep(root->rt))>1)//深度之差大于一就转 { if(num>=root->lt->data)///比左子根大,转两次,即LR { root=LR(root); } else ///比左子根小,转一次,即LL { root=LL(root); } } } else///比根大 { root->rt=Insert(root->rt, num);///加到右子树上 if(abs(deep(root->lt)-deep(root->rt))>1) { if(num>=root->rt->data)///加到右子树的右边,转一次,RR { root=RR(root); } else///加到右子树的左边,转两次,RL { root=RL(root); } } } } root->high=max(deep(root->lt), deep(root->rt))+1; return root; } int main() { struct node *root=NULL; int n, num; scanf("%d", &n); while(n--) { scanf("%d", &num); root=Insert(root, num); } printf("%d\n", root->data); return 0; }
Problem Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Sample Input
5 88 70 61 96 120
Sample Output
70