1123 Is It a Complete AVL Tree

题目大意

按照给出的顺序将节点插入一棵二叉树中,使得这棵树成为二叉平衡搜索树。最后输出层序遍历,并判断是否是一棵完全二叉树。

思路解析

把AVL树调整代码敲上去就可以了,需要牢记模板。

关于AVL树的有关讲解请移步:点击这里


示例代码

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct node{
public:
	int val;
	struct node* left, *right;
};
node* LLRotation(node* k1) {
	node* k2 = k1->left;
	k1->left = k2->right;
	k2->right = k1;	
	return k2;
}
node* RRRotation(node* k1) {
	node* k2 = k1->right;
	k1->right = k2->left;
	k2->left = k1;
	return k2;
}
node* LRRotation(node* k1) {
	k1->left = RRRotation(k1->left);
	node* k3 = LLRotation(k1);
	return k3;
}
node* RLRotation(node* k1) {
	k1->right = LLRotation(k1->right);
	node* k2 = RRRotation(k1);
	return k2;
}
int getHeight(node* nod) {
	if (nod == NULL) return 0;
	return max(getHeight(nod->left), getHeight(nod->right)) + 1;//注意+1
}
node* insert(node* root,int val) {
	if (root == NULL) {
		root = new node();
		root->val = val;
		return root;
	}
	if ( val < root->val) {
		root->left = insert(root->left, val);
		if (getHeight(root->left) - getHeight(root->right) == 2) {//左子树失衡
			if (val < root->left->val)
				root = LLRotation(root);
			else 
				root = LRRotation(root);
		}
	}
	else {
		root->right = insert(root->right, val);
		if (getHeight(root->left) - getHeight(root->right) == -2) {
			if (val < root->right->val) 
				root = RLRotation(root);
			else 
				root = RRRotation(root);
		}
	}
	return root;
}
vector<vector<int>> res(20);
vector<int> com;
int maxdeep = 0;
void level(node* root, int deep, int count) {
	if (root == NULL) return;
	res[deep].push_back(root->val);
	com.push_back(count);
	if (deep > maxdeep) maxdeep = deep;
	level(root->left, deep + 1, 2 * count + 1);
	level(root->right, deep + 1, 2 * count + 2);
}
int main() {
	int n,val;
	scanf("%d", &n);
	node* root = NULL;
	for (int i = 0; i < n; i++) {
		scanf("%d", &val);
		root = insert(root, val);
	}
	level(root, 0, 0);
	for (int i = 0; i <= maxdeep; i++) {
		for (int j = 0; j < res[i].size(); j++) {
			if (i == 0 && j == 0) 
				printf("%d", res[i][j]);
			else 
				printf(" %d", res[i][j]);
		}
	}
	printf("\n");
	sort(com.begin(), com.end());
	int i;
	for (i = 0; i < n && com[i] == i; i++);
	if (i == n) 
		printf("YES\n");
	else
		printf("NO\n");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值