1123 Is It a Complete AVL Tree (30 分)-PTA甲级-AVL树模板题

这篇博客介绍了如何在平衡二叉搜索树(AVL树)中进行节点插入,并保持树的平衡。通过leftRotation和rightRotation函数实现单旋转,以及leftRightRotation和rightLeftRotation函数实现双旋转来调整树的平衡。最后,使用BFS遍历展示树的节点。
摘要由CSDN通过智能技术生成
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
typedef long long ll;
const int maxn = 1e2 + 5, inf = 1e9;
struct node
{
	int num;
	node *left = nullptr, *right = nullptr;
};
int get_height(node *t)
{
	if (t == nullptr)
		return 0;
	return max(get_height(t->left), get_height(t->right)) + 1;
}
node* leftRotation(node *t)
{
	auto tmp = t->right;
	t->right = tmp->left;
	tmp->left = t;
	return tmp;
}
node* rightRotation(node *t)
{
	auto tmp = t->left;
	t->left = tmp->right;
	tmp->right = t;
	return tmp;
}
node* leftRightRotation(node *t)
{
	t->left=leftRotation(t->left);
	return rightRotation(t);
}
node* rightLeftRotation(node *t)
{
	t->right=rightRotation(t->right);
	return leftRotation(t);
}
void insert_node(node *&t, int num)
{
	if (t == nullptr)
	{
		t = new node;
		t->num = num;
		return;
	}
	if (t->num > num)
	{
		insert_node(t->left, num);
		int hl = get_height(t->left), hr = get_height(t->right);
		if (hl - hr >= 2)
		{
			if (t->left->num > num)
				t=rightRotation(t);
			else
				t=leftRightRotation(t);

		}
	}
	else
	{
		insert_node(t->right, num);
		int hl = get_height(t->left), hr = get_height(t->right);
		if (hr - hl >= 2)
		{
			if (t->right->num > num)
				t=rightLeftRotation(t);
			else
				t=leftRotation(t);
		}
	}
}
void BFS(node *t,int n)
{
	queue<node *> q;
	q.push(t);
	bool flag = true;
	while (!q.empty()&&n)
	{
		auto p = q.front();
		q.pop();
		if (p != nullptr)
		{
			cout << p->num;
			if (--n)
				cout << " ";
			q.push(p->left);
			q.push(p->right);
		}
		else
			flag = false;
	}
	cout << (flag ? "\nYES" : "\nNO");
}
int main()
{
	int n,tmp;
	cin >> n;
	node *t = nullptr;
	for (int i = 0; i < n; i++)
	{
		cin >> tmp;
		insert_node(t,tmp);
	}	
	BFS(t,n);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值