数据结构上机实验之二分查找之平衡二叉树
来源:互联网 发布:ubuntu 安装lnmp 编辑:程序博客网 时间:2024/05/29 10:44
数据结构上机实验之二分查找
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;}
阅读全文
0 0
- 数据结构上机实验之二分查找之平衡二叉树
- 数据结构上机实验之二分查找
- SDUT 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- [2039]数据结构上机实验之二分查找
- sdut数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找
- 数据结构上机实验之二分查找 SDUT
- emWin 2天速成实例教程005_控件聚焦和用户消息的使用方法
- 初识Android图片加载之Glide
- Luogu P2679 [NOIp提高组2015]子串
- jquery_01
- 最大流DFS(EK)算法模板
- 数据结构上机实验之二分查找之平衡二叉树
- 优先队列
- Pandas知识点(五)
- linux安装jdk以及eclipse,安装Anaconda与pyChram
- 51Nod-1711平均数(二分+树状数组|线段树)
- 算法竞赛入门——6174问题
- [NOIP2016]魔法阵 T4
- mysql 添加中文数据出现乱码的解决方法
- mysql(四/2)表的操作