1066. Root of AVL Tree (25)
来源:互联网 发布:淘宝服装店铺简介范文 编辑:程序博客网 时间:2024/06/05 19:29
#include<cstdio>#include<algorithm>using namespace std;#define maxn 30struct node{ int v,heigth; node *lchild,*rchild;};int data[maxn]={0},n;node* newN(int x){ node* now = new node; now->v = x; now->heigth = 1; now->lchild = now->rchild = NULL; return now;}int getHeight(node* root){ if(root == NULL) return 0; return root->heigth;}int getBF(node* root){ return getHeight(root->lchild) - getHeight(root->rchild);}void updateHeigth(node* root){ root->heigth = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;}//右旋Rvoid R(node* &root){ //获取左孩子 node* lchild = root->lchild; //root的左孩子变为lchild的右孩子 root->lchild = lchild->rchild; //root变为lchild的右孩子 lchild->rchild = root; //更新root和孩子的高度 updateHeigth(root); updateHeigth(lchild); //吧孩子变为根节点 root = lchild;}//左旋Lvoid L(node* &root){ //获取左孩子 node* rchild = root->rchild; //root的左孩子变为lchild的右孩子 root->rchild = rchild->lchild; //root变为lchild的右孩子 rchild->lchild = root; //更新root和孩子的高度 updateHeigth(root); updateHeigth(rchild); //吧孩子变为根节点 root = rchild;}void insert(node* &root,int x){ //空,这里插入 if(root == NULL) { root = newN(x); return; } //小于根,左边 if(x < root->v) { //递归插入 insert(root->lchild,x); //更新高度 updateHeigth(root); //获取平衡因子 if(getBF(root) == 2) { //2 1直接R if(getBF(root->lchild) == 1) { R(root); } else if(getBF(root->lchild) == -1) { //先L,lchild,在R L(root->lchild); R(root); } } } //大于根,右边 else { //递归插入 insert(root->rchild,x); //更新高度 updateHeigth(root); //获取平衡因子 if(getBF(root) == -2) { //2 1直接R if(getBF(root->rchild) == -1) { L(root); } else if(getBF(root->rchild) == 1) { //先L,lchild,在R R(root->rchild); L(root); } } }}node* creat(int data[], int n){ node* root = NULL; for(int i=0 ;i<n; i++) { insert(root, data[i]); } return root;}int main(){ node* root; scanf("%d",&n); for(int i=0; i<n; i++) scanf("%d",&data[i]); root = creat(data, n); printf("%d",root->v); return 0;}
0 0
- 【PAT】1066. Root of AVL Tree (25)
- 【PAT】1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- PAT 1066. Root of AVL Tree (25)
- PAT 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- pat 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1066. Root of AVL Tree (25)
- 1064. Complete Binary Search Tree (30)
- Jquery对<s:radio list="#{1:'是',0:'否'}" name=""></s:radio>清空设置
- ubuntu下xampp+dvwa安装到登入全过程
- poi导入数据
- 界面交互设计与表的约束
- 1066. Root of AVL Tree (25)
- 剑指offer-59.按之字形顺序打印二叉树
- 2017UESTC 数据结构专题题解
- Android Studio 结合 ButterKnife Zelezny 高效使用 Butterknife(黄油刀)
- JavaScript语言基础---(十五)应用编程练习--制作二级下拉菜单
- Qt中foreach的用法
- c++之指针一
- 1067. Sort with Swap(0,*) (25)
- 【设计模式】简单工厂模式