二叉排序树模板
struct tree
{
int data;
struct tree *left, *right;
}*root;
int flag;
struct tree *insertree(struct tree *root, int x)
{
if(!root)
{
root = (struct tree *)malloc(sizeof(struct tree));
root->data = x;
root->left = root->right = NULL;
}
else
{
if(root->data > x)
root->left = insertree(root->left, x);
else root->right = insertree(root->right, x);
}
return root;
}
void judge(struct tree *root1, struct tree *root2)
{
if(root1==NULL&&root2==NULL)
return ;
else if(root1&&root2)
{
if(root1->data == root2->data)
{
flag++;
judge(root1->left, root2->left);
judge(root1->right, root2->right);
}
else return ;
}
}
平衡二叉树 AVL 模板
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct tree
{
int data,h;
tree *left,*right;
};
int heigh(tree*root)
{
if(root==NULL)return 0;
else return root->h;
}
tree*L_L(tree*root)
{
tree*a=root;
tree*b=root->left;
a->left=b->right;
b->right=a;
a->h=max(heigh(a->left),heigh(a->right))+1;
b->h=max(heigh(b->left),heigh(b->right))+1;
return b;
}
tree*R_R(tree*root)
{
tree*a=root;
tree*b=root->right;
a->right=b->left;
b->left=a;
a->h=max(heigh(a->left),heigh(a->right))+1;
b->h=max(heigh(b->left),heigh(b->right))+1;
return b;
}
tree*R_L(tree*root)
{
tree*a=root,*b=a->right,*c=b->left;
a->right=c->left;
b->left=c->right;
c->left=a;
c->right=b;
a->h=max(heigh(a->left),heigh(a->right))+1;
b->h=max(heigh(b->left),heigh(b->right))+1;
c->h=max(heigh(c->left),heigh(c->right))+1;
return c;
}
tree*L_R(tree*root)
{
tree*a=root,*b=a->left,*c=b->right;
b->right=c->left;
a->left=c->right;
c->left=b;
c->right=a;
a->h=max(heigh(a->left),heigh(a->right))+1;
b->h=max(heigh(b->left),heigh(b->right))+1;
c->h=max(heigh(c->left),heigh(c->right))+1;
return c;
}
tree*insert_x(tree*root,int x)
{
if(root==NULL)
{
root=new tree;
root->h=0;
root->data=x;
root->left=root->right=NULL;
}
else
{
if(x<root->data)
{
root->left=insert_x(root->left,x);
if(heigh(root->left)-heigh(root->right)==2)
{
if(x<root->left->data)
{
root=L_L(root);
}
else
{
root=L_R(root);
}
}
}
else
{
root->right=insert_x(root->right,x);
if(heigh(root->left)-heigh(root->right)==-2)
{
if(x>root->right->data)
{
root=R_R(root);
}
else root=R_L(root);
}
}
}
root->h=max(heigh(root->left),heigh(root->right))+1;
return root;
}
int main()
{
int n;
scanf("%d",&n);
tree*root;
root=NULL;
for(int i=1;i<=n;i++)
{
int t;
scanf("%d",&t);
root=insert_x(root,t);
}
printf("%d\n",root->data);
return 0;
}