1123 Is It a Complete AVL Tree (30分)

题目链接:1123 Is It a Complete AVL Tree (30分)

题意

根据给出的序列建一颗平衡二叉树,并判断是否为完全二叉树

分析

构建平衡二叉树基于左单旋和右单旋。平衡因子的的绝对值超过1.左子树减去右子树的绝对值。
平衡因子为2

  1. 若左子树的平衡因子为1则进行右单旋。
  2. 若左子树的平衡因子为-1则先对左子树进行左单旋,在对本树进行右单旋。
    平衡因子为-2
  3. 若右子树的平衡因子为-1则进行左单旋。
  4. 若右子树的平衡因子为1则先对右子树进行右单旋,在对本树进行左单旋。

深搜判断是否为完全二叉树。

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct Tree{
	int data;
	struct Tree *ltree, *rtree;
}Tree;
int maxVal = 0;
void dfs(Tree *root, int index);
void bfs(Tree *root);
void addNode(Tree *&root, int x);
int getFac(Tree *root);
void RR(Tree *&root);
void LL(Tree *&root);
int getHigh(Tree *root);
int main(int argc, char** argv) {
	int n, x;
	scanf("%d", &n);
	Tree *root = NULL;
	for (int i = 0; i < n; i++) {
		scanf("%d", &x);
		addNode(root, x);
	}
	bfs(root);
	dfs(root, 1);
	if (maxVal == n)
		printf("YES\n");
	else
		printf("NO\n");
	return 0;
}
void dfs(Tree *root, int index) {
	if (root == NULL)
		return ;
	if (index > maxVal) {
		maxVal = index;
	}
	if (root->ltree)
		dfs(root->ltree, index * 2);
	if (root->rtree)
		dfs(root->rtree, index * 2 + 1);
}
void bfs(Tree *root) {
	queue<Tree*> que;
	que.push(root);
	int cnt = 0;
	while(!que.empty()) {
		cnt++;
		Tree *base = que.front();
		que.pop();
		if (base->ltree)
			que.push(base->ltree);
		if (base->rtree)
			que.push(base->rtree);
		if (cnt == 1)
			printf("%d", base->data);
		else
			printf(" %d", base->data);
	}
	printf("\n");
}
void addNode(Tree *&root, int x) {
	if (root == NULL) {
		root = (Tree *) malloc(sizeof(Tree));
		root->data = x;
		root->ltree = root->rtree = NULL;
		return ;
	}
	if (root->data > x) {
		addNode(root->ltree, x);
		if (getFac(root) == 2) {
			if (getFac(root->ltree) == 1) {
				RR(root);
			} else if (getFac(root->ltree) == -1) { // LR
				LL(root->ltree);
				RR(root);
			}
		}
	} else {
		addNode(root->rtree, x);
		if (getFac(root) == -2) {
			if (getFac(root->rtree) == 1) { // RL
				RR(root->rtree);
				LL(root);
			} else if (getFac(root->rtree) == -1) {
				LL(root);
			}
		}
	}
}
int getFac(Tree *root) {
	return getHigh(root->ltree) - getHigh(root->rtree);
}
void RR(Tree *&root) {
	Tree *t = root->ltree;
	root->ltree = t->rtree;
	t->rtree = root;
	root = t;
}
void LL(Tree *&root) {
	Tree *t = root->rtree;
	root->rtree = t->ltree;
	t->ltree = root;
	root = t;
}
int getHigh(Tree *root) {
	if (root == NULL)
		return 0;
	int l = getHigh(root->ltree);
	int r = getHigh(root->rtree);
	return l > r ? l + 1 : r + 1;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值