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

数据结构上机实验之二分查找
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)
        {
            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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值