摘要:本文主要向大家介绍了JAVA程序实例的数据结构查找实验之平衡二叉树代码实例,通过具体的内容向大家展示,希望对大家学习JAVA程序实例有所帮助。
本文主要向大家介绍了JAVA程序实例的数据结构查找实验之平衡二叉树代码实例,通过具体的内容向大家展示,希望对大家学习JAVA程序实例有所帮助。
Problem Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Example Input
5
88 70 61 96 120
Example Output
#include<bits .h="">
using namespace std;
struct node
{
int data;
int height;
node *left;
node *right;
};
int height(node *root)
{
if(root==NULL)return 0;
return root->height;
}
node* LL(node *root)
{
node* temp;
temp=root->left;
root->left=temp->right;
temp->right=root;
root->height=max(height(root->left),height(root->right))+1;
temp->height=max(height(temp->left),height(temp->right))+1;
return temp;
}
node* RR(node *root)
{
node*temp;
temp=root->right;
root->right=temp->left;
temp->left=root;
root->height=max(height(root->left),height(root->right))+1;
temp->height=max(height(temp->left),height(temp->right))+1;
return temp;
}
node* LR(node *root)
{
root->left=LL(root->left);
return LL(root);
}
node* RL(node *root)
{
root->right=RR(root->right);
return RR(root);
}
node* creat(node *root,int data)
{
if(root==NULL)
{
root=new node;
root->data=data;
root->left=root->right=NULL;
root->height=1;
}
else if(data>root->data)
{
root->right=creat(root->right,data);
if(height(root->right)-height(root->left)==2)
{
if(data>root->right->data)root=RR(root);
else root=RL(root);
}
}
else if(data<root->data)
{
root->left=creat(root->left,data);
if(height(root->left)-height(root->right)==2)
{
if(data>root->left->data)root=LR(root);
else root=LL(root);
}
}
root->height=max(height(root->left),height(root->right))+1;
return root;
}
int main()
{
node *root=NULL;
int num;
cin>>num;
for(int i=0;i<num;i++) cin="" int="">>data;
root=creat(root,data);
}
printf("%d\n",root->data);
}
</num;i++)></root-></bits>
希望对JAVA有兴趣的朋友有所帮助。了解更多内容,请关注职坐标编程语言JAVA频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号