|
藍森林 http://www.lslnet.com 2006年6月6日 10:18
AVL 樹-----------為這裡加點資源
[code]
#include <iostream>;
using namespace std;
//node of AVL Tree
struct node
{
int key;
int height;
node *left, *right;
//constructor
node(int k=0, node* l=NULL, node* r=NULL, int h=0):
key(k), left(l), right(r), height(h) {}
};
typedef node* AVL_Tree;
int node_height(node* p)
{
return p? p->;height:-1;
}
int Max(int a, int b)
{
return a >; b? a : b;
}
void calculate_height(node*& p)
{
p->;height = 1 +
Max(node_height(p->;left), node_height(p->;right));
}
void single_rotation_left(node*& k1)
{
node* k2 = k1->;left;
k1->;left = k2->;right;
k2->;right = k1;
calculate_height(k1);
calculate_height(k2);
k1 = k2;
}
void single_rotation_right(node*& k1)
{
node* k2 = k1->;right;
k1->;right = k2->;left;
k2->;left = k1;
calculate_height(k1);
calculate_height(k2);
k1 = k2;
}
void double_rotation_left(node*& k1)
{
single_rotation_right(k1->;left);
single_rotation_left(k1);
}
void double_rotation_right(node*& k1)
{
single_rotation_left(k1->;right);
single_rotation_right(k1);
}
void insert(AVL_Tree& t, int x)
{
if(t==NULL)
t = new node(x);
else if(x < t->;key)
{
insert(t->;left, x);
if(node_height(t->;left) - node_height(t->;right)==2)
if(x < t->;left->;key)
single_rotation_left(t);
else
double_rotation_left(t);
else
calculate_height(t);
}
else if(x >; t->;key)
{
insert(t->;right, x);
if(node_height(t->;right) - node_height(t->;left)==2)
if(x >; t->;right->;key)
single_rotation_right(t);
else
double_rotation_right(t);
else
calculate_height(t);
}
//else x is in the tree already
}
int height(AVL_Tree t)
{
return t->;height;
}
//another function to calculate the height of any tree
int height1(AVL_Tree t)
{
if(t==NULL)
return -1;
else
return Max(height1(t->;left), height1(t->;right)) + 1;
}
void inorder(AVL_Tree t)
{
if(t!=NULL)
{
inorder(t->;left);
cout<<t->;key<<" ";
inorder(t->;right);
}
}
int main()
{
AVL_Tree t = NULL;
for(int i=0; i<10000; i++)
insert(t, i);
cout<<"Height: "<<height1(t)<<endl;
}[/code] |
AVL 樹-----------為這裡加點資源
有查詢嗎? |
AVL 樹-----------為這裡加點資源
| |
|