数据结构实验之查找二:平衡二叉树
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
Hint
#include<bits/stdc++.h>
using namespace std;
typedef int element;
struct tree
{
element data;
int deep;
tree *lchild, *rchild;
};
int Max(int a, int b)
{
return a>b?a:b;
}
int Deep(tree *root)
{
if(!root)
return -1;
else
return root->deep;
}
tree *LL(tree *root) //右旋
{
tree *p = root->lchild;
root->lchild = p->rchild;
p->rchild = root;
p->deep = Max(Deep(p->lchild), Deep(p->rchild))+1;
root->deep = Max(Deep(root->lchild), Deep(root->rchild))+1;
return p;
}
tree *RR(tree *root) //左旋
{
tree *p = root->rchild;
root->rchild = p->lchild;
p->lchild = root;
p->deep = Max(Deep(p->lchild), Deep(p->rchild))+1;
root->deep = Max(Deep(root->lchild), Deep(root->rchild))+1;
return p;
}
tree *LR(tree *root) //先左旋后右旋
{
root->lchild = RR(root->lchild);
return LL(root);
}
tree *RL(tree *root) //先右旋后左旋
{
root->rchild = LL(root->rchild);
return RR(root);
}
tree *Creat(tree *root, int n)
{
if(!root)
{
root = new tree;
root->data = n;
root->deep = 0;
root->lchild = root->rchild = NULL;
}
else
{
if(n<root->data)
{
root->lchild = Creat(root->lchild, n);
if(Deep(root->lchild)-Deep(root->rchild)>1)
{
if(root->lchild->data > n)
root = LL(root);
else
root = LR(root);
}
}
else if(n>root->data)
{
root->rchild = Creat(root->rchild, n);
if(Deep(root->rchild)-Deep(root->lchild)>1)
{
if(root->rchild->data<n)
root = RR(root);
else
root = RL(root);
}
}
}
root->deep = Max(Deep(root->lchild), Deep(root->rchild)) + 1;
return root;
}
int main()
{
int n,m;
tree *root = NULL;
cin>>n;
for(int i = 0; i < n; i++)
{
cin>>m;
root = Creat(root,m);
}
cout<<root->data<<endl;
return 0;
}