数据结构实验之查找二:平衡二叉树
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 <algorithm> #include <stdlib.h> using namespace std; struct node { int h; int data; node *lchild,*rchild; }; int depth(node *root) { if(root==NULL) return 0; return root->h; } node * LL(node *p)//右转 { node *q; q=p->lchild; p->lchild=q->rchild; q->rchild=p; q->h=max(depth(q->lchild),depth(q->rchild))+1; p->h=max(depth(p->lchild),depth(p->rchild))+1; return q; } node * RR(node *p)//左转 { node *q; q=p->rchild; p->rchild=q->lchild; q->lchild=p; q->h=max(depth(q->lchild),depth(q->rchild))+1; p->h=max(depth(p->lchild),depth(p->rchild))+1; return q; } node * RL(node *p)//先右转后左转 { p->rchild= LL(p->rchild); return RR(p); } node * LR(node *p)//先左转后右转 { p->lchild= RR(p->lchild); return LL(p); } node * Insert(node * root,int k) { if(root==NULL) { root=(struct node *)malloc(sizeof(struct node)); root->data=k; root->lchild=root->rchild=NULL; root->h=1; } else { if(k<root->data) { root->lchild=Insert(root->lchild,k); if(depth(root->lchild)-depth(root->rchild)>1) { if(root->lchild->data>k) root= LL(root); else root=LR(root); } } else { root->rchild=Insert(root->rchild,k); if(depth(root->rchild)-depth(root->lchild)>1) { if(root->rchild->data<k) root= RR(root); else root=RL(root); } } } root->h=max(depth(root->lchild),depth(root->rchild))+1; return root; } node* creat(node *root,int n) { for(int i=0; i<n; i++) { int k; scanf("%d",&k); root=Insert(root,k); } return root; } int main() { int n; scanf("%d",&n); node *root; root=NULL; root=creat(root,n); printf("%d\n",root->data); }