数据结构实验之查找二:平衡二叉树
Time Limit: 400ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
输入
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
输出
输出平衡二叉树的树根。
示例输入
5
88 70 61 96 120
示例输出
Time Limit: 400ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
输入
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
输出
输出平衡二叉树的树根。
示例输入
5
88 70 61 96 120
示例输出
70
参考博文:http://blog.youkuaiyun.com/zhang_di233/article/details/50346377
<pre name="code" class="cpp">/*
1:建树的形式还是二叉树的形式但是一旦加入新节点,就要判断是否出现失衡点
若出现则根据此时树的状态进行相应的旋转调整.
2:平衡二叉树的的平衡因子只能是 1 0 -1
3:失衡时树的状态有4种 :http://www.tutorialspoint.com/data_structures_algorithms/avl_tree_algorithm.htm 个人觉得讲的很清晰.
4:建立的树是 左子树的所有结点值 < 根结点的值 < 右子树所有节点值.
*/
# include <bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
int height;//记录该节点在树中的高度
struct node*l,*r;
} Node;
int height(Node*p)
{
if(p==NULL)
return -1;
else
return p->height;
}
Node*right_rotation(Node*p) // LL型进行右旋
{
Node*p1;
p1 = p->l;
p->l = p1->r;//
p1->r = p;
p->height = max(height(p->l),height(p->r))+1;
p1->height = max(height(p1->l),p->height) + 1;
return p1;
}
Node*left_rotation(Node*p)//RR型进行左旋
{
Node*p1;
p1 = p->r;
p->r = p1->l;
p1->l = p;
p->height = max( height(p->l),height(p->r) ) + 1;
p1->height = max( height(p1->r),p->height) + 1;
return p1;
}
Node*left_right_rotation(Node*p) // LR型先左旋再右旋
{
p->l = left_rotation(p->l);//失衡节点下的第一个非失衡点进行左旋
return right_rotation(p); //失衡点右旋
}
Node*right_left_rotation(Node*p)
{
p->r = right_rotation(p->r);//失衡节点下的第一个非失衡点进行右旋
return left_rotation(p);//失衡点右旋
}
Node*Insert(Node*p,int key)
{
if(p==NULL)
{
p = (Node*)malloc(sizeof(Node));
p->data = key;
p->height = 0;
p->l = p->r = NULL;
}
else if(p->data > key)
{
p->l = Insert(p->l,key);
if(height(p->l) - height(p->r) == 2)
{
if(p->l->data > key)
p = right_rotation(p);
else
p = left_right_rotation(p);
}
}
else if(p->data < key)
{
p->r = Insert(p->r,key);
if(height(p->l) - height(p->r) == -2)
{
if(p->r->data < key)
p = left_rotation(p);
else
p = right_left_rotation(p);
}
}
p->height = max(height(p->l),height(p->r)) + 1;
return p;
}
int main()
{
int n;
int key;
while(~scanf("%d",&n))
{
Node*root = NULL;
while(n--)
{
scanf("%d",&key);
root = Insert(root,key);
}
printf("%d\n",root->data);
}
return 0;
}