多而不难的 Root of AVL Tree

An AVL tree is a self-balancing binary search tree. In an AVL tree,
the heights of the two child subtrees of any node differ by at most
one; if at any time they differ by more than one, rebalancing is done
to restore this property. Figures 1-4 illustrate the rotation rules.
LLrotation
RRRotation
RLRotation
LRRotation Now
given a sequence of insertions, you are supposed to tell the root of
the resulting AVL tree.

本题目要求是实现一棵平衡树并返回操作后该二叉平衡树的根节点。题面给出了四种在插入过程中旋转树的例子。所以很容易想到,在插入每个节点之后进行判断,若不平衡(左右节点的高度差为2),则判断其结构符合何种旋转特性,分类讨论后进入旋转的函数即可。只要细心地把每一个部分都实现就大功告成了。
代码如下

#include <iostream>
using namespace std;
struct Tree {
	int val=0;
	Tree* left=NULL;
	Tree* right=NULL;
};
inline int max(int a, int b) { return a > b ? a : b; }

Tree* LLRotation(Tree* node)//见图
{
	Tree* A = node;
	Tree* B = node->left;
	Tree* BR = B->right;
	B->right = A;
	A->left = BR;
	return B;
};
Tree* LRRotation(Tree* node)//见图
{
	Tree* A = node;
	Tree* B = node->left;
	Tree* BR = B->right;
	Tree* C = B->right;
	Tree* CL = C->left;
	Tree* CR = C->right;
	C->left = B;
	C->right = A;
	B->right = CL;
	A->left = CR;
	return C;
}
Tree* RRRotation(Tree* node)//见图
{
	Tree* A = node;
	Tree* B = node->right;
	Tree* BL = B->left;
	Tree* BR = B->right;
	Tree* AR = A->right;
	B->left = A;
	A->right = BL;
	B->right = BR;
	return B;
}
Tree* RLRotation(Tree* node)//见图
{
	Tree* A = node;
	Tree* B = node->right;
	Tree* BL = B->right;
	Tree* AR = A->right;
	Tree* C = B->left;
	Tree* CL = C->left;
	Tree* CR = C->right;
	C->left = A;
	C->right = B;
	A->right = CL;
	B->left = CR;
	return C;
}
int getHeight(Tree* root)
{
	if (!root)
		return 1;
	return 1 + max(getHeight(root->left), getHeight(root->right));
}

Tree* addTreeNode(Tree* root, int val)
{
	if (!root)
	{
		Tree* newTree = new Tree;
		newTree->val = val;
		return newTree;
	}
	if (val > root->val)
	{
		root->right = addTreeNode(root->right,val);
		if (getHeight(root->right) - getHeight(root->left) == 2)
		{
			if (root->right->val < val)
			{
				root = RRRotation(root);//祖祖孙孙都在右的话进RR
			}
			else
			{
				root = RLRotation(root);//爷爷的儿子在右、孙子在儿子的左边的话用RL
			}
		}
		return root;
	}
	else if (val < root->val)
	{
		root->left =  addTreeNode(root->left, val);
		if (getHeight(root->left) - getHeight(root->right) == 2)
		{
			if (root->left->val > val)
			{
				root = LLRotation(root);//祖祖孙孙都靠左进LL
			}
			else
			{
				root = LRRotation(root);//爷爷的儿子在左,孙子在儿子的右边
			}
		}
		return root;
	}
}
int main()
{
	int N;
	cin >> N;
	Tree* OriTree=new Tree;
	OriTree = NULL;
	for (int i = 0; i < N; i++)
	{
		int val;
		cin >> val;
		OriTree = addTreeNode(OriTree, val);
	}
	cout << OriTree->val << endl;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值