数据结构实验之查找二:平衡二叉树
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
相关文章推荐
- 数据结构实验之查找二:平衡二叉树
- 数据结构实验之查找二:平衡二叉树
- 数据结构实验之查找二:平衡二叉树
- 数据结构实验之查找二:平衡二叉树
- 3374 数据结构实验之查找二:平衡二叉树
- 数据结构实验之查找二:平衡二叉树
- 3374 数据结构实验之查找二:平衡二叉树
- 数据结构实验之查找二:平衡二叉树
- 数据结构实验之查找二:平衡二叉树
- SDTU(3374) 数据结构实验之查找二:平衡二叉树
- 数据结构实验之查找二:平衡二叉树
- 数据结构实验之查找二:平衡二叉树【OJ--3374】
- 数据结构实验之查找二:平衡二叉树
- 3374-数据结构实验之查找二:平衡二叉树
- sdutacm-数据结构实验之查找二:平衡二叉树
- 数据结构实验之查找二:平衡二叉树
- SDUT 3374 数据结构实验之查找二:平衡二叉树
- (模板题)sdut 3374 数据结构实验之查找二:平衡二叉树(平衡二叉树的建立)
- 数据结构实验之查找二:平衡二叉树
- SDUT-3374 数据结构实验之查找二:平衡二叉树