平衡二叉树的实现

简介: 平衡二叉树的实现

平衡二叉树是对排序二叉树的优化,在插入结点时有着很大的变化,需要调整树的高度达到平衡,下面是代码:

#include<iostream>
using namespace std;
struct node{
  int v,height; //height 记录高度 这里的高度是从下往上记 
  node *lchild,*rchild;
};
node* newnode(int x){   //生成一个新结点 
  node* r=new node;
  r->v=x;
  r->height=1;      //初始化高度为一 
  r->lchild=r->rchild=NULL;
  return r;
}
int getheight(node* root) {  // 得到当前结点的高度 
  if(root==NULL)return 0;
  return root->height;
}
int getfactor(node* root){  //得到平衡因子 
  return getheight(root->lchild)-getheight(root->rchild);
}
void updateheight(node* root) {  //更新结点当前高度 
root->height=max(getheight(root->lchild),getheight(root->rchild))+1;
  //左右子树较大者加一 
}
void search(node* root,int x) { // 查找操作不变 
  if(root==NULL){  //没有查到 
    printf("fail!\n");
    return;
  }
  if(root->v==x){ //查到 
    printf("succeed!");
    return;
  }
  if(root->v>x)search(root->lchild,x);
  else search(root->rchild,x);
}
//为实现插入操作的四个旋
void L(node* &root) {//左旋,root的右孩子当根 
  node* temp=root->rchild;
  root->rchild=temp->lchild; 
  temp->lchild=root; 
  //更新这两个结点高度 
  updateheight(root);
  updateheight(temp);
  root=temp;//改变根结点 
}
void R(node* &root) {//右旋,root的左孩子当根 
  node* temp=root->lchild;
  root->lchild=temp->rchild;
  temp->rchild=root; 
  updateheight(root);
  updateheight(temp);
  root=temp;
}
/*四种树形结论,看平衡因子 
根为2 左孩子为1,LL型      右旋解决 
      左孩子为 -1,LR型    先左孩子左旋后root右旋解决 
根为-2  右孩子-1,RR型   左旋解决 
        右孩子1,RL型    先右孩子右旋再root左旋解决
*/    
void insert(node* &root,int x){
  if(root==NULL){
  root=newnode(x);
  return; 
  }
  if(x<root->v) {
    insert(root->lchild,x);//往左子树插 
    updateheight(root);//更新高度
    if(getfactor(root)==2) {
      if(getfactor(root->lchild)==1)//LL型,右旋 
      R(root) ;
      else { //LR型,左右旋 
        L(root->lchild) ;
        R(root);
      }
    }
  }
  else{
    insert(root->rchild,x);//往右子树插 
    updateheight(root);//更新高度
    if(getfactor(root)==-2) {
      if(getfactor(root->rchild)==-1)//RR型,左旋 
      L(root) ;
      else { //RL型,右左旋 
        R(root->rchild) ;
        L(root);
      }
    }
  }
}
node * creating(int a[],int n){  //创建二叉树 
  node* root=NULL;
  for(int i=0;i<n;i++)
  insert(root,a[i]);
  return root;  
}
int main(){
  return 0;
} 

这里和排序二叉树的区别在于引入了高度好标记平衡因子,高度的更新操作比较重要,之后左、右旋,记录树形解决方法也是难点。

相关文章
|
16小时前
二叉搜索树
二叉搜索树
12 2
|
16小时前
|
C++
平衡二叉树(C++)
平衡二叉树(C++)
19 1
|
16小时前
|
存储 安全 C++
C++【二叉搜索树】
C++【二叉搜索树】
41 0
|
7月前
51 # 二叉搜索树的实现
51 # 二叉搜索树的实现
18 0
|
9月前
|
编译器 C语言 C++
【C++】二叉搜索树
【C++】二叉搜索树
41 0
|
9月前
|
算法
平衡二叉树(AVL树)
平衡二叉树(AVL树)
51 0
|
9月前
|
存储
【二叉搜索树】
【二叉搜索树】
34 0
|
10月前
|
存储 算法 关系型数据库
有了二叉树,平衡二叉树为什么还需要红黑树
有了二叉树,平衡二叉树为什么还需要红黑树
66 0
有了二叉树,平衡二叉树为什么还需要红黑树
|
11月前
|
算法
二叉搜索树、平衡二叉树
一、二叉搜索树 这里我们不用太多书面化的语言来定义,笔者认为在讨论数据结构、算法相关的内容时用太多书面化、学术化的语言是一种让人很烦的事情。咬文嚼字,不便于读者理解。 简单来说二叉树搜索树,其实就是用来做二分查找的一种二叉树。 特点是:根节点的左子树值均小于根节点的值,根节点的右子树值均大于根节点的值。 比如123 4 567建树的结果就是
38 0
|
12月前
|
C++
【C++】二叉搜索树(上)
【C++】二叉搜索树
48 0