数据结构之二叉树之平衡二叉树
来源:互联网 发布:淘宝上牛排都是假的 编辑:程序博客网 时间:2024/06/01 08:18
建立平衡二叉树:
建利平衡二叉树的关键的是要搞清楚关键步骤,首先判断平衡因子,如果等于2或者-2,就要开始旋转了,旋转主要有四种类型,左左旋,左右旋,右右旋,右左旋。这里就不一一解释了,网上好多介绍如何旋转的。
ps:对于我来说的难点。函数里面调用函数,始终有点晕,搞不清楚原理。从网上看了好多代码,最后终于搞清了原理,也最终写出了平衡二叉树。
直接上代码:
#include <stdio.h>#include <stdlib.h>typedef struct BiTNode{ int data; int bf; struct BiTNode *lchild,*rchild;}BiTNode,*BiTree;//计算深度的函数,int BiTDepth(BiTree root){ int depth,rdepth,ldepth; if(!root) depth = 0; else { ldepth = BiTDepth(root->lchild); rdepth = BiTDepth(root->rchild); if(ldepth>rdepth) depth = ldepth + 1; else depth = rdepth +1; } return depth;}//计算平衡因子的函数。int max(BiTree root){ return BiTDepth(root->lchild)-BiTDepth(root->rchild);}BiTree R_Rotate(BiTree root){ BiTree L=root->lchild; /*L 指向*T 左子树根结点*/ root->lchild=L->rchild; /*L 的右子树挂接*T 的左子树*/ L->rchild = root; root=L; return root; /* *L 指向新的根结点*/}BiTree L_Rotate(BiTree root){ BiTree Lr=root->rchild; /*Lr 指向*T 右子树根结点*/ root->rchild=Lr->lchild; /*L 的左子树挂接*p 的右子树*/ Lr->lchild=root; root=Lr; //printf("%d ",root->rchild->data); return root; /* *L 指向新的根结点*/}//左平衡函数//先判断不平衡节点的下一个节点的平衡因子。如果平衡因子为1,说明左边插入,说明是左左型,//如果是-1,说明是右右型,右边插入BiTree Leftbalance(BiTree root){ BiTree l = root->lchild; switch(l->bf) { case 1: root = R_Rotate(root); break; case -1: l = L_Rotate(l); root->lchild = l; root = R_Rotate(root); break; } return root;}// 右平衡函数,同理左平衡函数。BiTree Rightbalance(BiTree root){ BiTree r = root->rchild; switch(r->bf) { case -1: root = L_Rotate(root); break; case 1: r = R_Rotate(r); root->rchild = r; root = L_Rotate(root); break; } return root;}//创建二叉树的过程。函数里面调用函数//新建的节点平衡因子一定为0 ,建好后,返回上一个节点。即新节点的双亲节点,并计算该节点的平衡因子,//不断向上找。直到找到平衡因子为2或-2的节点,然后进行平衡。 BiTree Creat(BiTree root,int m) { if(root == NULL) { root = (BiTree)malloc(sizeof(BiTNode)); root->data = m; root->lchild = root->rchild = NULL; root-> bf = 0; return root; } else if(m<root->data) { root->lchild = Creat(root->lchild,m); root->bf = max(root); if(root->bf==2) root = Leftbalance(root); } else { root->rchild = Creat(root->rchild,m); root->bf = max(root); if(root->bf==-2) root = Rightbalance(root); } return root; }int main(){ int n; scanf("%d",&n); BiTree root = NULL; while(n--) { int m; scanf("%d",&m); root = Creat(root,m); } printf("%d\n",root->data); return 0;}
阅读全文
0 0
- 数据结构之平衡二叉树
- 数据结构之 平衡二叉树
- 数据结构之平衡二叉树
- 数据结构之平衡二叉树
- 数据结构之平衡二叉树
- 数据结构之平衡二叉树
- 数据结构之平衡二叉树
- 数据结构之平衡二叉树
- 数据结构之二叉树之平衡二叉树
- 【数据结构】平衡二叉树之AVL树
- 数据结构之(平衡二叉树)
- 数据结构之平衡二叉树AVL
- 数据结构之红黑树与平衡二叉树
- 数据结构系列之平衡二叉树
- 数据结构之 平衡二叉树的建立
- 数据结构之平衡二叉树(红黑树)
- 数据结构-平衡二叉树之-红黑树
- 数据结构上机实验之二分查找之平衡二叉树
- cocos2d.3.10导入安卓项目相关问题笔记
- JAVA各种系统架构图及其简介
- 翻转单词顺序列
- Android 获取cache缓存的目录路径
- 剑指offer——20.包含min函数的栈
- 数据结构之二叉树之平衡二叉树
- Linux系统卸载openjdk 安装jdk
- java io 操作
- Spring(18)——使用Java类的形式配置bean
- Html隐藏占空间与隐藏不占空间
- ELK系统系列 2——Logstash的安装使用&性能调优
- Java中Calendar类的简单使用方法,以及日期格式化的方法,字符串日期格式的验证
- 命名管道的创建和使用
- js中Array.sort()实现原理