您的位置:首页 > 理论基础 > 数据结构算法

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

2016-08-13 14:02 295 查看


题目描述

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


输入

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


输出

输出平衡二叉树的树根。#include<iostream>
using namespace std;
typedef struct node
{
int data;
int dp;
struct node *lchild,*rchild;
}Tree;
int deep(Tree *root)
{
if(!root)
return -1;
else
return root->dp;
}
int max1(int x,int y)
{
return x>y?x:y;
}
Tree *LL(Tree *root)
{
Tree *key=root->lchild;
root->lchild=key->rchild;
key->rchild=root;
root->dp=max1(deep(root->lchild),deep(root->rchild))+1;
key->dp=max1(deep(key->lchild),deep(key->rchild))+1;
return key;
}
Tree *RR(Tree *root)
{
Tree *key1=root->rchild;
root->rchild=key1->lchild;
key1->lchild=root;
root->dp=max1(deep(root->lchild),deep(root->rchild))+1;
key1->dp=max1(deep(key1->lchild),deep(key1->rchild))+1;
return key1;
}
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 x)
{
if(!root)
{
root=new Tree();
root->data=x;
root->lchild=root->rchild=NULL;
}
else
{
if(x<root->data)
{
root->lchild=creat(root->lchild,x);
if(deep(root->lchild)-deep(root->rchild)>1)//这里要注意,当左右子树满足这个条件是,其实根节点的深度还没有更新呢。
{
if(x<root->lchild->data)//左左的情况
root=LL(root);
else
root=LR(root);
}
}
else
{
root->rchild=creat(root->rchild,x);
if(deep(root->rchild)-deep(root->lchild)>1)
{
if(x>root->rchild->data)
root=RR(root);
else
root=RL(root);
}
}
}
root->dp=max1(deep(root->lchild),deep(root->rchild))+1;//这里每插入一个节点就要更新它的深度。
return root;
}
void front(Tree *root)//用来检测的
{
if(root)
{
front(root->lchild);
cout<<root->data<<" ";
front(root->rchild);
}
}
int main()
{
int n,i,x;
Tree *root=NULL;
cin>>n;
for(i=1;i<=n;i++)
{
cin>>x;
root=creat(root,x);
}
//front(root);
cout<<root->data<<endl;
return 0;
}


示例输入

5
88 70 61 96 120



示例输出

70
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: