平衡二叉树是任意结点左右子树的深度相差不超过1的二叉树,已知一棵二叉树采用二叉链表存储,结点结构为(left,data,right),root指向根结点。请编写算法判断二叉树是否是一棵平衡二叉树。
解题思路:jt
设置二叉树的平衡标记为balance,以标记返回二叉树bt是否为平衡二叉树,若为平衡二叉树,则返回1,否则返回0;h为二叉树bt的高度。采用后序遍历的递归算法:
1.若bt为空,则高度为0,balance=1;
2.如bt仅有根结点,则高度为1,balance=1;
3.否则,对bt的左、右子树执行递归运算,返回左、右子树的高度和平衡标记,bt的高度为最高子树的高度加1.若左、右子树的高度差大于1,则吧balance=0;若左、右子树的高度差小于等于1,且左右子树都平衡时,balance=1,否则balance=0。
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<string>
using namespace std;
//string qx="123" ;//非平衡二叉树测试数据
//string zx="321";
string qx="123";//平衡二叉树测试数据
string zx="213";
const int MaxSize=100;
typedef struct Tree//二叉树结构定义
{
int data;
Tree *left;
Tree *right;
} *BiTree;
BiTree build(string qx,string zx)//建树
{
if(qx.size()==0)return NULL;
Tree *root=(Tree *)malloc(sizeof(Tree));
root->data=qx[0]-'0';
int pos=zx.find(qx[0]);
root->left=build(qx.substr(1,pos),zx.substr(0,pos));
root->right=build(qx.substr(pos+1),zx.substr(pos+1));
return root;
}
void BT(BiTree bt,int &balance,int &h)//判断是否是平衡二叉树
{
int bl=0,br=0,hl=0,hr=0;//左右子树的平衡标记和高度
if(bt==NULL)
{
h=0;
balance=1;
}
else if(bt->left==NULL&&bt->right==NULL)
{
h=1;
balance=1;
}
else
{
BT(bt->left,bl,hl);//递归判断左子树
BT(bt->right,br,hr);//递归判断右子树
if(abs(hl-hr)<2) balance=1;//若左右子树高度差为0或1,则为平衡二叉树
else balance=0;
h=(hl>hr?hl:hr)+1;
}
}
int main()
{
int balance=0,h=0;
BiTree T=build(qx,zx);
BT(T,balance,h);
printf("%d %d",balance,h);
}