C++ 平衡树判定

算法思想:

利用递归的后序遍历过程:
  ①判断左子树是否平衡
  ②判断右子树是否平衡
  ③判断以该节点为根的树是否平衡
判断条件:左子树和右子树均为平衡树且高度差的绝对值<=1 
void Judge_AVL(BTree T,int &balance,int &height)
{
	int bl=0,br=0,hl=0,hr=0;//左右子树的平衡性和高度
	if(T==NULL)//递归出口:遍历到空节点退出递归
	{
		height=0;//空节点高度为0
		balance=1;//平衡
	}
	else if(T->lchild==NULL&&T->rchild==NULL)//递归出口:遍历到叶节点退出递归
	{
		height=1;//叶节点高度为1
		balance=1;//平衡
	}
	else
	{
		Judge_AVL(T->lchild,bl,hl);//递归左子树
		Judge_AVL(T->rchild,br,hr);//递归右子树
		height=max(hl,hr)+1;//根的高度为子树高度的最大值
		if(abs(hl-hr)<=1&&bl==1&&br==1)//子树高度差<=1且左右子树都平衡
			balance=1;//整棵树平衡
		else
			balance=0;//树不平衡
	}
}

运行代码


#include "stdafx.h"
#include<iostream>
using namespace std;

typedef struct BNode
{
	int data;
	struct BNode* lchild,*rchild;
}BNode,*BTree;
int Insert(BTree &T,int k);//插入
void Creat(BTree &T,int *s,int n);//创建
void Judge_AVL(BTree T,int &balance,int &height);//平衡二叉树的判定
int _tmain(int argc, _TCHAR* argv[])
{
	BTree t1,t2,t3;int balance,height;
	int a[5]={1,2,3,4,5};
	int b[5]={4,3,2,1,5};
	int c[5]={3,1,2,4,5};
	Creat(t1,a,5);
	
	Judge_AVL(t1,balance,height);
	if(balance==1)
		cout<<"高度为:"<<height<<",是平衡二叉树"<<endl;
	else
		cout<<"高度为:"<<height<<",非平衡二叉树"<<endl;
	Creat(t2,b,5);
	Judge_AVL(t2,balance,height);
	if(balance==1)
		cout<<"高度为:"<<height<<",是平衡二叉树"<<endl;
	else
		cout<<"高度为:"<<height<<",非平衡二叉树"<<endl;
	Creat(t3,c,5);
	Judge_AVL(t3,balance,height);
	if(balance==1)
		cout<<"高度为:"<<height<<",是平衡二叉树"<<endl;
	else
		cout<<"高度为:"<<height<<",非平衡二叉树"<<endl;
	system("pause");
	return 0;
}
int Insert(BTree &T,int k)
{
	if(T==NULL)
	{
		T=new BNode;
		T->data=k;
		T->lchild=T->rchild=NULL;
		return 1;
	}
	if(T->data==k)
		return 0;
	else if(k < T->data)
		Insert(T->lchild,k);
	else
		Insert(T->rchild,k);
}
void Creat(BTree &T,int *s,int n)
{
	T=NULL;
	for(int i=0;i<n;i++)
	{
		Insert(T,s[i]);
	}
}
void Judge_AVL(BTree T,int &balance,int &height)
{
	int bl=0,br=0,hl=0,hr=0;//左右子树的平衡性和高度
	if(T==NULL)
	{
		height=0;//空节点高度为0
		balance=1;//平衡
	}
	else if(T->lchild==NULL&&T->rchild==NULL)
	{
		height=1;//叶节点高度为1
		balance=1;//平衡
	}
	else
	{
		Judge_AVL(T->lchild,bl,hl);//递归左子树
		Judge_AVL(T->rchild,br,hr);//递归右子树
		height=max(hl,hr)+1;//根的高度为子树高度的最大值
		if(abs(hl-hr)<=1&&bl==1&&br==1)//子树高度差的绝对值<=1且左右子树都平衡
			balance=1;//整棵树平衡
		else
			balance=0;//树不平衡
	}
}

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值