平衡二叉樹(AVL)模板
阿新 • • 發佈:2019-01-30
#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; }