数据结构实验之查找二:平衡二叉树
2015-12-04 11:27
155 查看
数据结构实验之查找二:平衡二叉树
Time Limit: 400MS Memory limit: 65536K
题目描述
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。输入
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。输出
输出平衡二叉树的树根。示例输入
5 88 70 61 96 120
示例输出
70 /*【平衡二叉树的定义】左右子树的高度之差不能大于1 */#include <algorithm> #include <iostream> #include <numeric> #include <cstring> #include <iomanip> #include <string> #include <vector> #include <cstdio> #include <queue> #include <stack> #include <cmath> #include <map> #include <set> //#define LL long long const int M = 1001000; const double esp = 1e-6; const double PI = 3.14159265359; const int INF = 0x3f3f3f3f; using namespace std; typedef struct AVLNode { int height; int data; AVLNode *lc; AVLNode *rch; }*Node; int height(Node p){ //返回平衡二叉树的高度 if(p==NULL) return -1; else return p->height; } //平衡二叉树的左左旋转 Node LL(Node p2){ Node p1; p1=p2->lc; p2->lc=p1->rch; p1->rch=p2; p2->height=max(height(p2->lc),height(p2->rch))+1; p1->height=max(height(p1->lc),p2->height)+1; return p1; } //平衡二叉树的右右旋转 Node RR(Node t2){ Node t1; t1=t2->rch; t2->rch=t1->lc; t1->lc=t2; t2->height=max(height(t2->lc),height(t2->rch))+1; t1->height=max(height(t1->rch),t2->height)+1; return t1; } //平衡二叉树左转右 Node L_R(Node p3){ p3->lc=LL(p3->lc); return LL(p3); } //平衡二叉树右转左 Node R_L(Node t3){ t3->rch=RR(t3->rch); return RR(t3); } //平衡二叉树的插入节点 Node Insert(Node root,int x){ if(root==NULL){ root=(Node)malloc(sizeof(struct AVLNode)); root->data=x; root->height=0; root->lc=root->rch=NULL; } else if(x < root->data){ root->lc=Insert(root->lc,x); if(height(root->lc)-height(root->rch)==2){ if(x < root->lc->data) root=LL(root); else root=L_R(root); } } else if(x > root->data){ root->rch=Insert(root->rch,x); if(height(root->rch)-height(root->lc)==2){ if(x>root->rch->data) root=RR(root); else root=L_R(root); } } root->height=max(height(root->lc),height(root->rch))+1; return root; } int main(){ int n,x; while(~scanf("%d",&n)){ Node root=NULL; for(int i=0; i<n; i++){ scanf("%d",&x); root = Insert(root,x); } printf("%d\n",root->data);//输出根节点 } return 0; }
相关文章推荐
- 自己编写的一个数据结构,类似优先级队列
- 数据结构--二叉树按层次建立和按层次输出二叉树的内容
- 数据结构上机实验dfs&&bfs遍历图
- 数据结构实验之查找四:二分查找
- 第十二周--数据结构-图的遍历之深度优先遍历求解问题
- 数据结构
- 【第14周—查找项目1-2——验证分块查找算法】
- C++设计模式 之 “数据结构” 模式:Composite、Iterator、Chain of Resposibility
- 数据结构实验之图论八:欧拉回路
- LeetCode148 Sort List
- 数据结构之Huffman树与最优二叉树
- 数据结构--向量--归并排序
- 数据结构实验图论一:基于邻接矩阵的广度优先搜索遍历
- 不同级数复杂度的计算
- Persistent Data Structures(可持久化的数据结构)和源码
- 计算机基础算法及数据结构综述
- 数据结构实验之查找七:线性之哈希表
- Android 打造任意层级树形控件 考验你的数据结构和设计
- SDUT 3373 数据结构实验之查找一:二叉排序树
- 数据结构实验之查找三:树的种类统计