1066. Root of AVL Tree (25)

#include <iostream>
#include <stdlib.h>

using namespace std;

typedef struct node
{
	int key, bf;
	struct node *lchild, *rchild;
}*bnode;

void rrotate(bnode *root)
{
	bnode l = (*root)->lchild;
	bnode lr = l->rchild;

	(*root)->lchild = lr;
	l->rchild = *root;
	*root = l;
}

void lrotate(bnode *root)
{
	bnode r = (*root)->rchild;
	bnode rl = r->lchild;

	(*root)->rchild = rl;
	r->lchild = *root;
	*root = r;
}

void rbalance(bnode *root)
{
	bnode r = (*root)->rchild;
	int rbf = r->bf;

	bnode rl = r->lchild;
	int rlbf;

	if(rbf == 1)
	{
		(*root)->bf = r->bf = 0;
		lrotate(root);
	}
	else if(rbf == -1)
	{
		rlbf = rl->bf;

		if(rlbf == 0)
		{
			(*root)->bf = r->bf = 0;
		}
		else if(rlbf == -1)
		{
			(*root)->bf = 0;
			r->bf = 1;
		}
		else
		{
			(*root)->bf = -1;
			r->bf = 0;
		}

		rl->bf = 0;
		rrotate(&((*root)->rchild));
		lrotate(root);
	}
}

void lbalance(bnode *root)
{
	bnode l = (*root)->lchild;
	int lbf = l->bf;

	bnode lr = l->rchild;
	int lrbf;

	if(lbf == -1)
	{
		(*root)->bf = l->bf = 0;
		rrotate(root);
	}
	else if(lbf == 1)
	{
		lrbf = lr->bf;

		if(lrbf == 0)
		{
			(*root)->bf = l->bf = 0;
		}
		else if(lrbf == 1)
		{
			(*root)->bf = 0;
			l->bf = -1;
		}
		else
		{
			(*root)->bf = 1;
			l->bf = 0;
		}

		lr->bf = 0;
		lrotate(&((*root)->lchild));
		rrotate(root);
	}
}

int avlinsert(bnode *root, int key, int &taller)
{
	int rootkey, rootbf;

	if(*root == NULL)
	{
		*root = (bnode) malloc (sizeof(node));

		(*root)->key = key;
		(*root)->bf = 0;
		(*root)->lchild = (*root)->rchild = NULL;

		taller = 1;
	}
	else
	{
		rootkey = (*root)->key;
		rootbf = (*root)->bf;

		if(key < rootkey)
		{
			if(avlinsert(&((*root)->lchild), key, taller) == 0)
			{
				return 0;
			}

			if(taller == 1)
			{
				if(rootbf == -1)
				{
					lbalance(root);
					taller = 0;
				}
				else if(rootbf == 0)
				{
					(*root)->bf = -1;
					taller = 1;
				}
				else
				{
					(*root)->bf = 0;
					taller = 0;
				}
			}
		}
		else
		{
			if(avlinsert(&((*root)->rchild), key, taller) == 0)
			{
				return 0;
			}

			if(taller == 1)
			{
				if(rootbf == -1)
				{
					(*root)->bf = 0;
					taller = 0;
				}
				else if(rootbf == 0)
				{
					(*root)->bf = 1;
					taller = 1;
				}
				else
				{
					rbalance(root);
					taller = 0;
				}
			}
		}
	}

	return 1;
}

int main()
{
	int n;
	scanf("%d", &n);

	int key, i, taller;
	bnode root = NULL;

	for(i = 1; i <= n; i++)
	{
		scanf("%d", &key);
		avlinsert(&root, key, taller);
	}

	printf("%d\n", root->key);

	system("pause");
	return 0;
}

 

posted on 2025-11-23 17:13  王景迁  阅读(0)  评论(0)    收藏  举报

导航