PAT 甲级 1123 Is It a Complete AVL Tree (30 分)

Note

  • AVL树构造 – 层序遍历 – 判断完全二叉树

Code

#include<bits/stdc++.h>
using namespace std;

struct node{
	int data, height;
	node *left, *right;
};

node* newnode(int n) {
	node* root = new node;
	root->data = n;
	root->left = root->right = NULL;
	return root;
}

int getheight(node* root) {
	if(root == NULL) return 0;
	return max(getheight(root->left), getheight(root->right)) + 1;
}

int getfactor(node* root) {
	if(root == NULL) return 0;
	return getheight(root->left) - getheight(root->right);
}

void L(node* &root) {
	node *root_right = root->right;
	root->right = root_right->left;
	root_right->left = root;
	root = root_right;
	return ;
}

void R(node* &root) {
	node *root_left = root->left;
	root->left = root_left->right;
	root_left->right = root;
	root = root_left;
	return ;
}

void insert(node* &root, int val) {
	if(root == NULL) {
		root = newnode(val);
		return ;
	}
	else {
		if(val < root->data) {
			insert(root->left, val);
		}
		else {
			insert(root->right, val);
		}
		
		int fac = getfactor(root);
		if(fac == 2) {
			int fac_left = getfactor(root->left);
			if(fac_left == 1) {
				R(root); 
			}
			else if(fac_left == -1) {
				L(root->left);
				R(root);
			}
		}
		else if(fac == -2) {
			int fac_right = getfactor(root->right);
			if(fac_right == -1) {
				L(root); 
			}
			else if(fac_right == 1) {
				R(root->right);
				L(root);
			}
		}
		
	}
}

vector<int> ans;
void bfs(node* root) {
	queue<node*> q;
	q.push(root);
	while(!q.empty()) {
		node *t = q.front();
		q.pop();
		ans.push_back(t->data);
		if(t->left) q.push(t->left);
		if(t->right) q.push(t->right);
	}
}

bool check(node *root, int n, int loc) {
	if(root == NULL && loc <= n) return false;
	if(root == NULL || loc >= 2 * n + 1) return true;
	return check(root->left, n, loc * 2) && check(root->right, n, loc * 2 + 1);
}

int main() {
	#ifndef ONLINE_JUDGE
	freopen("data.txt", "r", stdin);
	#endif
	
	int n, val;
	cin >> n;
	node *root = NULL;
	for(int i = 0; i < n; i++) {
		cin >> val;
		insert(root, val);		
	}
	
	bfs(root);
	for(int i = 0; i < n; i++) {
		if(i != 0) printf(" ");
		printf("%d", ans[i]);
	}
	
	if(check(root, n, 1)) printf("\nYES");
	else printf("\nNO");
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值