平衡二叉树(AVL)模板
2017-06-10 17:17
344 查看
模板代码:
#include <bits/stdc++.h> using namespace std; const int maxn = 1e2+5; int data[maxn]; struct node{ int v,height; node *lchild, *rchild; }; node* newNode(int v){ node* Node = new node; Node->v = v; Node->height = 1; Node->lchild = Node->rchild = NULL; return Node; } int getHeight(node *root){ if (root == NULL) return 0; else return root->height; } int getBlanceFactor(node* root){ return getHeight(root->lchild) - getHeight(root->rchild); } void upDateHeight(node *root){ root->height = max(root->lchild->height, root->rchild->height) + 1; return ; } void search_v(node *root, int v){ if (root == NULL){ printf("search failed!!\n"); return; } if (v == root->v){ cout<<v<<endl; } else if (v < root->v){ search_v(root->lchild, v); } else{ search_v(root->rchild, v); } return; } void L(node* &root){//这里一定要加引用的符号,否则在改变根节点的时候不会影响全局~ node* temp = root->rchild; root->rchild = temp->lchild; temp->lchild = root; upDateHeight(root); upDateHeight(temp); root = temp; return; } void R(node* &root){//这里一定要加引用的符号,否则在改变根节点的时候不会影响全局~ node* temp = root->lchild; root->lchild = temp->rchild; temp->rchild = root; upDateHeight(root); upDateHeight(temp); root = temp; return; } void insert_node(node* &root, int v){ if(root == NULL){ root = newNode(v); return; } if(v < root->v){ insert_node(root->lchild, v); upDateHeight(root); if (getBlanceFactor(root) == 2){ if (getBlanceFactor(root->lchild) == 1){ R(root); } else if(getBlanceFactor(root->lchild) == -1){ L(root->lchild); R(root); } } } else{ insert_node(root->rchild, v); upDateHeight(root); if (getBlanceFactor(root) == -2){ if (getBlanceFactor(root->rchild) == -1){ L(root); } else if(getBlanceFactor(root->rchild) == 1){ R(root->rchild); L(root); } } } return; } node* Create(int n){ node *root = NULL; for (int i=0; i<n; i++){ insert_node(root, data[i]); } return root; } int main() { int n; cin>>n; for (int i=0; i<n; i++){ cin>>data[i]; } node* root; root = Create(n); search_v(root, 5); return 0; }
相关文章推荐
- 平衡二叉树AVL操作模板
- STL源码笔记(18)—平衡二叉树AVL(C++封装+模板)
- 平衡二叉树(AVL)
- 数据结构中常见的树(BST二叉搜索树、AVL平衡二叉树、RBT红黑树、B-树、B+树、B*树)
- 红黑树与AVL(平衡二叉树)的区别
- 自创一种新的方法建立 平衡二叉树(AVL)
- 数据结构-平衡二叉树(AVL Tree)
- 平衡二叉树(AVL)图解与实现
- C++平衡二叉树(AVL)
- 平衡二叉树(AVL)
- 【证明可用】平衡二叉树(avl tree)的C语言实现
- 关于C++类库KYLib: 扩展平衡二叉树类(AVL extended tree)
- 判断一颗二叉树是否为平衡二叉树(AVL)
- pat1123 Is It a Complete AVL Tree,平衡二叉树的建立,完全二叉树判断,层序
- AVL 平衡二叉树
- 自己动手写数据结构:C++模板类 平衡二叉树 AVL
- SBT 平衡二叉树模板
- 关于C++类库KYLib: 用C语言实现平衡二叉树(AVL tree)的源码
- 数据结构中常见的树(BST二叉搜索树、AVL平衡二叉树、RBT红黑树、B-树、B+树、B*树)
- 平衡二叉树_AVLTree.c