PAT甲组1123 Is It a Complete AVL Tree思路解析和代码

A1123

题目链接

个人思路

本题考查平衡二叉树的构造+完全二叉树的判断,形式中规中矩,但是平衡二叉树的理解和编写确实不太容易!
判断完全二叉树,在A1110中已经有涉及,需要对树进行广搜遍历,过程中进行判断

个人思路代码

#include <bits/stdc++.h>
using namespace std;
int N;
struct Node{
	int data;
	int height;//当前子树的高度
	Node* left;
	Node* right; 
};
Node* newNode(int x)//新建节点
{
	Node* node = new Node;
	node->data = x;
	node->height = 1;//初始高度为1
	node->left = node->right = NULL;
	return node; 
}
int getHeight(Node* root)//获取当前节点的高度
{
	if(root == NULL)
		return 0;
	else
		return root->height;
}
int getBalanceFactor(Node* root)//获取当前节点的平衡因子
{
	return (getHeight(root->left) - getHeight(root->right));
}
void updateHeight(Node* root)//更新高度
{
	root->height = max(getHeight(root->left), getHeight(root->right)) + 1;
}
void LRotation(Node* &root)//左旋
{
	Node* temp = root->right;
	root->right = temp->left;
	temp->left = root;
	updateHeight(root);
	updateHeight(temp);
	root = temp;
}
void RRotation(Node* &root)//右旋
{
	Node* temp = root->left;
	root->left = temp->right;
	temp->right = root;
	updateHeight(root);
	updateHeight(temp);
	root = temp;
}
//根节点,要插入的值为x 
void insert(Node* &root, int x)
{
	if(root == NULL)
	{
		root = newNode(x);
		return;
	}
	if(x < root->data)//二叉搜索树插入判断
	{
		insert(root->left, x);
		updateHeight(root);
		if(getBalanceFactor(root) == 2)//树型判断,不同树型采用不同旋转
		{
			if(getBalanceFactor(root->left) == 1)
			{
				RRotation(root);
			}
			else if(getBalanceFactor(root->left) == -1)
			{
				LRotation(root->left);
				RRotation(root);
			}	
		}
	}
	else
	{
		insert(root->right, x);
		updateHeight(root);
		if(getBalanceFactor(root) == -2)
		{
			if(getBalanceFactor(root->right) == -1)
			{
				LRotation(root);
			}
			else if(getBalanceFactor(root->right) == 1)
			{
				RRotation(root->right);
				LRotation(root);
			}
		}
	}
}
bool isCmplt = true;//标记是否为完全二叉树 
bool isLeaf = false;//标记是否遍历到叶子节点 
void levelOrder(Node* root)
{
	queue<Node*> q;
	q.push(root);
	int cnt = 0;
	while(!q.empty())
	{
		Node* now = q.front();
		q.pop();
		printf("%d", now->data);
		cnt++;
		if(cnt < N)
			printf(" ");
		else
			printf("\n");
		//遍历判断完全二叉树	
		if(now->left == NULL && now->right != NULL)
			isCmplt = false;
		if(isLeaf == true)
		{
			if(now->left != NULL || now->right != NULL)//非叶子节点 
				isCmplt = false;
		}
		if(now->right == NULL)//后面应该均为叶子节点 
			isLeaf = true;	
		//广搜 
		if(now->left != NULL)
			q.push(now->left);
		if(now->right != NULL)
			q.push(now->right);
	}
}
int main(int argc, char *argv[]) {
	scanf("%d", &N);
	Node* root = NULL;
	for(int i = 0; i < N; ++i)
	{
		int x;
		scanf("%d", &x);
		insert(root, x); 
	}
	levelOrder(root);
	if(isCmplt == true)
		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、付费专栏及课程。

余额充值