平衡二叉树
来源:互联网 发布:框架图制作软件 编辑:程序博客网 时间:2024/05/16 13:51
数据结构实验之查找二:平衡二叉树
Time Limit: 400MS Memory limit: 65536K
题目描述
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
输入
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
输出
输出平衡二叉树的树根。
示例输入
588 70 61 96 120
示例输出
70
提示
来源
看了下网上的二叉树代码,感觉在RL和LR型插入的时候旋转的有错误,所以自己做了下改动!
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<malloc.h>struct node{ int data; int hight; struct node *lc,*rc;};int max(int x,int y){ if(x>y) { return x; } else { return y; }}//二叉树高度int depth(struct node *root){ if(root==NULL) { return -1; } else { return root->hight; }}//左子树的左子树节点插入,则进行右旋转(左左-->右转)struct node *LL(struct node *root){ struct node *tail; tail=root->lc; root->lc=tail->rc; tail->rc=root; root->hight=max(depth(root->lc),depth(root->rc))+1; return tail;};//右子树的右子树节点插入,则进行左旋转(右右-->左转)struct node *RR(struct node *root){ struct node *tail; tail=root->rc; root->rc=tail->lc; tail->lc=root; root->hight=max(depth(root->lc),depth(root->rc))+1; return tail;};//左子树的右子树节点插入,则先进行左旋转,再进行右旋转struct node *LR(struct node *root){ root->lc=RR(root->lc); return LL(root);};//右子树的左子树节点插入,则先进行右旋转,再进行左旋转struct node *RL(struct node *root){ root->rc=LL(root->rc); return RR(root);};//创建二叉树的过程struct node *creat(struct node *root,int e){ if(root==NULL) { root=(struct node *)malloc(sizeof(struct node)); root->data=e; root->lc=root->rc=NULL; root->hight=0; } else if(root->data>e) { root->lc=creat(root->lc,e); if((depth(root->lc)-depth(root->rc))>1) { if(root->lc->data>e) { root=LL(root); } else { root=LR(root); } } } else if(root->data<e) { root->rc=creat(root->rc,e); if((depth(root->rc)-depth(root->lc))>1) { if(root->rc->data<e) { root=RR(root); } else { root=RL(root); } } } root->hight=max(depth(root->lc),depth(root->rc))+1; return root;};int main(){ int n; scanf("%d",&n); int a[30]; struct node *root; root=NULL; for(int i=0;i<n;i++) { scanf("%d",&a[i]); root=creat(root,a[i]); } printf("%d\n",root->data); return 0;}
0 0
- 平衡二叉树平衡法则
- 二叉树--二叉平衡树
- 平衡二叉树的
- 平衡二叉树
- 平衡二叉树
- 平衡二叉树
- 平衡二叉树
- 平衡二叉查找树
- 平衡二叉树 详解
- 平衡二叉树
- 平衡二叉树
- AVL 平衡二叉树
- 平衡二叉树
- 平衡二叉树-红黑树
- 平衡二叉树
- 平衡二叉树
- 平衡二叉树
- 平衡二叉树
- iOS 多线程总结(一)
- PHP中 获取文件扩展名的N种方法
- TCP编程与UDP编程的步骤:
- Yii2创建程序更新和写入的日志捕捉
- HDU4793 2013 长沙 C (计算几何—点和圆的位置关系—解法①列方程求解[时间作自变量] —解法②向量积和sin角度求解长度再除以有方向的速度)
- 平衡二叉树
- Squares
- shareSDK分享_登陆
- 案例:e袋洗如何以用户为导向的高性价比闭环
- jsp页面跳转
- ASP.net mvc学习笔记
- maven配置默认的中央仓库,setting.xml配置
- 树-堆结构练习——合并果子之哈夫曼树
- androuid 安卓 popupwindow使用(新手必备)