1123 Is It a Complete AVL Tree (30 point(s))(AVL树:构造AVL以及判断是否为完全二叉树)

题目链接

思路?

①还是参考《算法笔记的AVL部分,做了一些代码上的简化(相比于另一道题
②完全二叉树的判断参考于这里

代码

using namespace std;
#include<bits/stdc++.h>
struct node {
	int data;
	node* left, * right;
	node(int d = 0) :data(d), left(NULL), right(NULL) {}
};
int getheight(node* n) {
	return n == NULL ? 0 : max(getheight(n->left), getheight(n->right)) + 1;
}
void L(node*& n) {
	node* temp = n->right;
	n->right = temp->left;
	temp->left = n;
	n = temp;
}
void R(node*& n) {
	node* temp = n->left;
	n->left = temp->right;
	temp->right = n;
	n = temp;
}
void insert(node*& n, int d) {
	if (n == NULL) {
		n = new node(d);
		return;
	}
	if (d < n->data) {
		insert(n->left, d);
		if (getheight(n->left)-getheight(n->right)==2) {
			if (d<n->left->data) R(n);
			else L(n->left), R(n);
		}
	}
	else if (d > n->data) {
		insert(n->right, d);
		if (getheight(n->left) - getheight(n->right) == -2) {
			if (d>n->right->data) L(n);
			else R(n->right), L(n);
		}
	}
}
bool traversal(node* n) {
	bool leaf = false, flag = true;
	queue<node*>waiting;
	waiting.push(n);
	while (!waiting.empty()) {
		node* temp = waiting.front();
		waiting.pop();
		if (waiting.empty() && !temp->left && !temp->right)cout << temp->data << endl;
		else cout << temp->data << " ";
		if ((leaf && (temp->left || temp->right)) || (!temp->left && temp->right)) flag = false;
		if (temp->left)waiting.push(temp->left);
		if (temp->right)waiting.push(temp->right);
		if ((!temp->right && !temp->left) || (temp->left && !temp->right))leaf = true;
	}
	return flag;
}
int main() {
	int n, temp;
	cin >> n;
	node* root = NULL;
	for (int i = 0; i < n; i++) {
		cin >> temp;
		insert(root, temp);
	}
	if (traversal(root))cout << "YES";
	else cout << "NO";
	return 0;
}

昨天做了人生第一道AVL,而今天这道…好像这就是甲级题库里最后一道avl了___*(  ̄皿 ̄)/#____giao

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值