1123 Is It a Complete AVL Tree (30分)

考察点,二叉平衡树、层序遍历和完全二叉树,与1066 Root of AVL Tree (25分)、1064 Complete Binary Search Tree (30分)、1110 Complete Binary Tree (25分)类似,没有难点(代码量比较大,真要在考场上写出这道题一定要对前面几个知识点有比较深的理解)。

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<vector>
using namespace std;
int n, temp,cnt;
bool flag;
struct node {
	int value,height;
	node *left, *right;
};

int height(node *root) {
	return root == NULL ? -1 : root->height;
}

node *ll(node *root) {
	node *left = root->left;
	root->left = left->right;
	left->right = root;
	root->height = max(height(root->left),height(root->right))+1;
	left->height = max(height(left->left),height(left->right))+1;
	return left;
}

node *rr(node *root) {
	node *right = root->right;
	root->right = right->left;
	right->left = root;
	root->height = max(height(root->left), height(root->right)) + 1;
	right->height = max(height(right->left), height(right->right)) + 1;
	return right;
}

node *lr(node *root) {
	root->left = rr(root->left);
	return ll(root);
}

node *rl(node *root) {
	root->right = ll(root->right);
	return rr(root);
}

node *insert(node *root,int value) {
	if (root == NULL) {
		root = new node;
		root->value = value;
		root->height = 0;
		root->left = root->right = NULL;
		return root;
	}
	if (value < root->value) {
		root->left = insert(root->left, value);
		if (height(root->left) - height(root->right) == 2) {
			if (value < root->left->value) root = ll(root);
			else root = lr(root);
		}
	}
	else {
		root->right = insert(root->right, value);
		if (height(root->right) - height(root->left) == 2) {
			if (value > root->right->value) root = rr(root);
			else root = rl(root);
		}
	}
	root->height = max(height(root->left), height(root->right)) + 1;
	return root;
}

int main() {
	cin >> n;
	node *root =NULL;
	for (int i = 0; i < n; i++) {
		cin >> temp;
		root = insert(root, temp);
	}
	queue<node*> q;
	vector<int> v;
	q.push(root);
	while (!q.empty()) {
		node *r = q.front();
		q.pop();
		if (r != NULL) {
			v.push_back(r->value);
			q.push(r->left);
			q.push(r->right);
		}
		else { 
			flag = true;
			continue;
		}
		cnt++;
		if (cnt == n)break;
	}
	for (int i = 0; i < n; i++) cout << (i == 0 ? "" : " ") << v[i];
	cout << endl << (flag?"NO":"YES");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值