1066. Root of AVL Tree (25)

来源:互联网 发布:js加密后怎么调用 编辑:程序博客网 时间:2024/06/02 05:33


#include<iostream>#include<cmath> //绝对值abs using namespace std; struct AVLNode{int data;AVLNode * lchild;AVLNode * rchild; int depth;AVLNode(int data=0){this->data=data;lchild=rchild=NULL;//左右孩子而非左右子树   depth=1;}/*法二:AVLNode(int v=0):data(v),left(NULL),right(NULL),depth(1){}  */}; //获取当前节点深度 int GetDepth(AVLNode * root){if(!root) return 0;return root->depth; } //判断当前节点是否平衡 bool IsBalanced(AVLNode * root){ //bool,没有boolean类型 return abs(GetDepth(root->lchild)-GetDepth(root->rchild))<2;} AVLNode * LLrotate(AVLNode * root){AVLNode * tmp=root->lchild; root->lchild=tmp->rchild;tmp->rchild=root;root->depth=(GetDepth(root->lchild)>GetDepth(root->rchild)?GetDepth(root->lchild):GetDepth(root->rchild))+1; tmp->depth=(GetDepth(tmp->lchild)>GetDepth(tmp->rchild)?GetDepth(tmp->lchild):GetDepth(tmp->rchild))+1; return tmp;//返回根节点 }AVLNode * RRrotate(AVLNode * root){AVLNode * tmp=root->rchild; root->rchild=tmp->lchild;tmp->lchild=root;root->depth=(GetDepth(root->lchild)>GetDepth(root->rchild)?GetDepth(root->lchild):GetDepth(root->rchild))+1; tmp->depth=(GetDepth(tmp->lchild)>GetDepth(tmp->rchild)?GetDepth(tmp->lchild):GetDepth(tmp->rchild))+1; return tmp;//返回根节点 }AVLNode * LRrotate(AVLNode * root){root->lchild=RRrotate(root->lchild);return LLrotate(root);//返回根节点 }AVLNode * RLrotate(AVLNode * root){root->rchild=LLrotate(root->rchild);return RRrotate(root);//返回根节点 }//插入节点 AVLNode * Insert(AVLNode * root,int data){if(!root){root=new AVLNode(data);return root;}if(data > root->data){    //1判断插入方向 root->rchild=Insert(root->rchild,data);   //cout<<"右孩子值:"<<root->rchild->data<<" ";  //2插入 if(!IsBalanced(root)){ //3如有不平衡,则旋转调整 if(data > root->rchild->data) root=RRrotate(root);else   root=RLrotate(root);}}else{root->lchild=Insert(root->lchild,data); //cout<<"左孩子值:"<<root->lchild->data<<" ";if(!IsBalanced(root)){if(data > root->lchild->data) root=LRrotate(root);else    root=LLrotate(root);}}root->depth=( GetDepth(root->lchild)>GetDepth(root->rchild)?GetDepth(root->lchild):GetDepth(root->rchild) )+1; //4更新高度 return root;} int main(){//freopen("input.txt","r",stdin);AVLNode * root;//只申明,会不会变成野指针? 会,但是后来Insert赋值,又变正常指针了 int n,data;cin>>n;while(n--){cin>>data;root=Insert(root,data);}cout<<root->data<<endl;return 0;}


原创粉丝点击