#include <bits/stdc++.h>
typedef struct node
{
int data;
struct node *l,*r,*par;
}*tree;
int length(tree root)
{
int cou=0,len1,len2;
if(root)
{
len1=length(root->l);
len2=length(root->r);
if(len1>=len2)
{
cou=len1;
cou++;
}
else
{
cou=len2;
cou++;
}
}
else
{
cou=0;
}
return cou;
}
tree RR(tree root) // ROOT的右边,向左转
{
tree p;
p=root->r;
root->r=p->l;
p->l=root;
return p;
}
tree LL(tree root)// ROOT的左边,向右转
{
tree p;
p=root->l;
root->l=p->r;
p->r=root;
return p;
}
tree RL(tree root)// ROOT的右边,先向右转在向左转
{
root->r=LL(root->r);
return RR(root);
}
tree LR(tree root)// ROOT的左边,先向左转在向右转
{
root->l=RR(root->l);
return LL(root);
}
tree creat(tree root ,int n)
{
int t,k;
root =new node;
root->l=NULL;
root->r=NULL;
root->par=NULL;
scanf("%d",&t);
root->data=t;
for(int i=1;i<n;i++)
{
scanf("%d",&k);
tree p;
p=root;
while(1)
{
if(k>p->data)
{
if(p->r)
{
p=p->r;
}
else
{
tree q;
q=new node;
q->l=NULL;
q->r=NULL;
q->data=k;
p->r=q;
q->par=p;
if(length(p->par->r)-length(p->par->l) > 1)
{
if(p->data < k)
{
root=RR(p->par);
root->par=NULL;
}
else
{
root=RL(p->par);
root->par=NULL;
}
}
break;
}
}
else
{
if(p->l)
{
p=p->l;
}
else
{
tree q;
q=new node;
q->data=k;
q->l=NULL;
q->r=NULL;
p->l=q;
q->par=p;
if(length(p->par->l)-length(p->par->r) > 1)
{
if(p->data < k)
{
root=LR(p->par);
root->par=NULL;
}
else
{
root=LL(p->par);
root->par=NULL;
}
}
break;
}
}
}
}
return root;
}
int main()
{
int n;
scanf("%d",&n);
tree root;
root=creat(root,n);
printf("%d\n",root->data);
return 0;
}
平衡二叉树 非递归(未完成)
最新推荐文章于 2022-09-02 16:08:04 发布