AVL--平衡二叉树的一些操作,杂记
来源:互联网 发布:淘宝客服认证考试 编辑:程序博客网 时间:2024/06/03 23:40
AVL–平衡二叉树的一些操作,杂记
//AVL--平衡二叉树的一些操作,杂记//平衡二叉树的定义//首先,AVL树仍然是一颗二叉查找树//AVL树的数据结构struct node{ int v,height; //v为结点权值,height为当前子树高度 node *lchild,*rchild; }; //新建一个结点//生成一个新结点,v为结点权值 node* new_node(int v) { node* Node=new node; Node->v=v; Node->height=1; Node->lchild = Node->rchild = NULL; return Node;}//获取根结点root的子树的当前heightint get_height(node* root) { if(root==NULL) { return 0; } return root->height;}//计算结点root的平衡因子int get_balance(node* root) { return get_height(root->lchild)-get_height(root->rchild);}//更新结点root的heightvoid update_height(node* root) { //max(左孩子的height,右孩子的height)+1 root->height=max(get_height(root->lchild),get_height(root->rchild))+1;}//AVL 的基本操作//1.查找操作//search函数查找AVL树 中数据域为x的结点void search(node* root,int x) { if(root==NULL) { printf("search failed\n"); //空树,查找失败 return; } if(x==root->data) //查找成功,访问 { printf("%d\n",root->data); } else if(x<root->data) { search(root->lchild,x); } else { search(root->rchild,x); }}//2.插入操作 //左旋void L(node* &root) { node* temp =root->rchild; root->rchild=temp->lchild; temp->lchild=root; update_height(root); update_height(temp); root=temp;}//右旋void R(node* &root) { node* temp=root->lchild; root->lchild=temp->rchild; temp->rchild=root; update_height(root); update_height(temp); root=temp;}//不考虑 平衡操作 的insert函数void insert(node* &root,int v){ if(root==NULL) { root=new_node(v); return; } if(v<root->v) { insert(root->lchild,v); } else { insert(root->rchild,v); }}//考虑加入 平衡操作的 insert函数//插入权值为v的结点void insert(node* &root,int v) { if(root==NULL) { root=new_node(v); return; } if(v < root->v) //v比根结点的权值小 { insert(root->lchild,v); //往左子树插入 update_height(root); //更新树高 if(get_balance(root) == 2 ) { if(get_balance(root->lchild ==1)) //LL型 { R(root); } else if(get_balance(root->lchild)== -1) //LRxing { L(root->lchild); R(root); } } } else //v比根结点的权值大 { insert(root->rchild,v); update_height(root); //更新树高 if(get_balance(root)==2) { if(get_balance(root->rchild)== -1) //RR型 { L(root); } else if(get_balance(root->rchild)==1) //RL型 { R(root->rchild); L(root); } } }}//AVL 树的 建立node* create(int data[] ,int n ) { node* root=NULL; for(int i=0;i<n;i++) { insert(root,data[i]); } return root; //返回根结点 }
阅读全文
0 0
- AVL--平衡二叉树的一些操作,杂记
- 平衡二叉树(AVL)的插入操作
- AVL---平衡二叉树的基本操作
- 平衡二叉树(AVL树)的基本操作
- 平衡二叉树AVL的基本操作之插入
- 平衡二叉树AVL的基本操作之删除
- 二叉平衡树AVL插入删除操作的实现
- 平衡二叉树(AVL)的介绍及基本操作
- AVL平衡二叉树(删除操作)
- AVL 平衡二叉树
- 平衡二叉树(AVL)
- 平衡二叉树(AVL)
- AVL 平衡二叉树
- avl平衡二叉树
- 二叉平衡树AVL
- 平衡二叉树(AVL)
- 平衡二叉树(AVL)
- 平衡二叉树 AVL
- IOError: [Errno 22] invalid mode ('r') or filename;错误的处理方法
- select 下拉框字体颜色设置
- jenkins中,maven打包报Can not execute Findbugs:java.lang.OutOfMemoryError:java heap spacek扫描错误
- Web前端的及基础常识
- iOS 正则处理 NSString,NSAttributedString
- AVL--平衡二叉树的一些操作,杂记
- 关闭NG-Bootstrap carousel 的箭头按钮和指示器
- 15 个开源的顶级人工智能工具
- 网络判断
- Android 6.0 如何添加完整的系统服务(app-framework-kernel)
- Ceph Crushmap新特性:class
- Qml上拉下拉刷新
- visual studio 2015安装 无法启动程序,因为计算机丢失D3DCOMPILER_47.dll 的解决方法
- Java 中的值传递