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

数据结构上机实验之二分查找之平衡二叉树

2017-08-14 13:43 495 查看
数据结构上机实验之二分查找

Time Limit: 1000MS Memory Limit: 65536KB

Submit Statistic Discuss

Problem Description

在一个递增的序列里,查找元素是否存在,若存在输出YES,不存在输出NO.

Input

本题多组数据,首先输入一个数字n(n>=100000),然后输入n个数,数据保证数列递增,然后再输入一个查找数字。

Output

若存在输出YES,不存在输出NO.

Example Input

4

1 3 5 8

3

Example Output

YES

Hint

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>

using namespace std;

typedef struct tree
{
int data;
int d;
tree *left;
tree *right;
}tree;

int max(int x,int y)
{
return x>y?x:y;
}

int deep(tree *root)
{
if(!root)
return -1;
return root->d;
}

void LL(tree *&root)
{
tree *p = root->left;
root->left = p->right;
p->right = root;
root->d = max(deep(root->left),deep(root->right)) + 1;
root = p;
}

void RR(tree *&root)
{
tree *p;
p = root->right;
root->right = p->left;
p->left = root;
root->d = max(deep(root->left),deep(root->right)) + 1;
root = p;
}

void LR(tree *&root)
{
RR(root->left);
LL(root);
}
void RL(tree *&root)
{
LL(root->right);
RR(root);
}

void create(tree *&root,int data)
{
if(!root)
{
root = (tree *)malloc(sizeof(tree));
root->d = 0;
root->data = data;
root->left = root->right = NULL;
}
else if(root->data>data)
{
create(root->left,data);
if(deep(root->left)-deep(root->right)>1)
{
if(root->left->data>data)
LL(root);
else
LR(root);
}
}
else if(root->data<data)
{
create(root->right,data);
if(deep(root->right)-deep(root->left)>1)
{
if(root->right->data<data)
RR(root);
else
RL(root);
}
}
root->d = max(deep(root->left),deep(root->right))+1;
}

int find(tree *root,int data)
{
if(root==NULL)
return 0;
else
{
if(root->data==data)
{
return 1;
}
else if(root->data>data)
{

4000
return find(root->left,data);
}
else if(root->data<data)
{
return find(root->right,data);
}
}
}

int main()
{
int n,m;
while(~scanf("%d",&n))
{
tree *root;
root = NULL;
for(int i = 0;i<n;i++)
{
int temp;
scanf("%d",&temp);
create(root,temp);
}
int temp;
scanf("%d",&temp);
int res = find(root,temp);
if(res)
{
printf("YES\n");
}
else
{
printf("NO\n");
}

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