PAT 1066. Root of AVL Tree

1. AVL树 维基百科

2. 别人的题解

参考了这两份资料,不得不说那位同学的AVL树写得很漂亮..  我之前试图用类来封装那些方法,写的跟屎一样。。


代码:

#include <iostream>
#include <cmath>

using namespace std;

struct Node
{
	Node *left;
	Node *right;
	int value;
	int height;
	Node(int val): left(0), right(0), value(val), height(0) {}
};

int get_height(Node* node)
{
	return node==0? -1: node->height;
}

bool is_balanced(Node *node)
{
	return abs(get_height(node->left)-get_height(node->right)) <= 1;
}

Node* rotate_right(Node* root)
{
	Node* new_root = root->left;
	root->left = new_root->right;
	new_root->right = root;
	root->height = max(get_height(root->left), get_height(root->right)) + 1;// cannot use "root->height = get_height(root);" here
	new_root->height = max(get_height(new_root->left), get_height(new_root->right)) + 1;
	return new_root;
}

Node* rotate_left(Node *root)
{
	Node* new_root = root->right;
	root->right = new_root->left;
	new_root->left = root;
	root->height = max(get_height(root->left), get_height(root->right)) + 1;// cannot use "root->height = get_height(root);" here
	new_root->height = max(get_height(new_root->left), get_height(new_root->right)) + 1;
	return new_root;
}

Node* insert(Node* root, int val)
{
	if (root == NULL)
	{
		return new Node(val);
	}
	if (val < root->value) // insert left
	{
		root->left = insert(root->left, val);
		if (is_balanced(root) == false)
		{
			if (val < root->left->value) // LL
			{				
				root = rotate_right(root);
			} else // LR
			{
				root->left = rotate_left(root->left); // attention!
				root = rotate_right(root);
			}
		}
	} else
	{
		root->right = insert(root->right, val);
		if (is_balanced(root) == false)
		{
			if (val > root->right->value) // RR
			{
				root = rotate_left(root);
			} else // RL
			{
				root->right = rotate_right(root->right); // attention!
				root = rotate_left(root);
			}
		}
	}
	root->height = max(get_height(root->left), get_height(root->right)) + 1;
	return root;
}

int main()
{
	int n, tmp;
	Node* root = NULL;

	cin >> n;
	while ( n -- )
	{
		cin >> tmp;
		root = insert(root, tmp);
	}
	cout << root->value;

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值