标签:c++
链接:
题意:
求依次插入N个带权节点的平衡二叉树最后的根节点的权是多少
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> using namespace std; typedef struct node{ int data; node *left,*right; int h; }*AVLtree; int max(int a,int b){ return a>b?a:b; } int Get_h(AVLtree T){ if(!T) return 0; else return T->h; } AVLtree SingleLeftRotation(AVLtree A){ //向右旋 AVLtree B=A->left; A->left=B->right; B->right=A; A->h=max(Get_h(A->left),Get_h(A->right))+1; B->h=max(Get_h(B->left),Get_h(B->right))+1; return B; } AVLtree SingleRightRotation(AVLtree A){ //向左旋 AVLtree B=A->right; A->right=B->left; B->left=A; A->h=max(Get_h(A->left),Get_h(A->right))+1; B->h=max(Get_h(B->left),Get_h(B->right))+1; return B; } AVLtree DoubleLeftRightRotation(AVLtree A){ //左节点左旋再整体右旋 A->left=SingleRightRotation(A->left); return SingleLeftRotation(A); } AVLtree DoubleRightLeftRotation(AVLtree A){ //右节点右旋再整体左旋 A->right=SingleLeftRotation(A->right); return SingleRightRotation(A); } AVLtree AVLTree_insert(AVLtree T,int x){ if(!T){ T=(AVLtree)malloc(sizeof(node)); T->data=x; T->left=T->right=NULL; T->h=1; //新节点的初始高度为1 return T; }else if(x<T->data){ T->left=AVLTree_insert(T->left,x); if(Get_h(T->left)-Get_h(T->right)==2){ if(x<T->left->data) //插在左节点的左边(右旋) T=SingleLeftRotation(T); else //插在左节点的右边(左旋右旋) T=DoubleLeftRightRotation(T); } }else{ T->right=AVLTree_insert(T->right,x); if(Get_h(T->left)-Get_h(T->right)==-2){ if(x>T->right->data) //插在右节点的右边(左旋) T=SingleRightRotation(T); else T=DoubleRightLeftRotation(T); //插在右节点的左边(右旋左旋) } } T->h=max(Get_h(T->left),Get_h(T->right))+1; //更新高度 return T; } int main(){ int n,x; AVLtree T=NULL; scanf("%d",&n); while(n--){ scanf("%d",&x); T=AVLTree_insert(T,x); } cout<<T->data<<endl; return 0; }
PAT1066 Root of AVL Tree 平衡二叉树的实现
标签:c++
原文地址:http://blog.csdn.net/axuan_k/article/details/45175207