算法思想:
利用递归的后序遍历过程:
①判断左子树是否平衡
②判断右子树是否平衡
③判断以该节点为根的树是否平衡
判断条件:左子树和右子树均为平衡树且高度差的绝对值<=1
void Judge_AVL(BTree T,int &balance,int &height)
{
int bl=0,br=0,hl=0,hr=0;
if(T==NULL)
{
height=0;
balance=1;
}
else if(T->lchild==NULL&&T->rchild==NULL)
{
height=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)
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;
balance=1;
}
else if(T->lchild==NULL&&T->rchild==NULL)
{
height=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)
balance=1;
else
balance=0;
}
}
运行结果
