递归解法:
(1)如果二叉树为空,返回真
(2)如果二叉树不为空,如果左子树和右子树都是AVL树并且左子树和右子树高度相差不大于1,返回真,其他返回假
参考代码:
/********************************************************* - Copyright (C): 2016 - File name : isavl.cpp - Author : - zxn - - Date : 2016年08月08日 星期一 12时53分51秒 - Description : * *******************************************************/
#include <iostream>
#include <cstdlib>
#define MAX 4
using namespace std;
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
typedef struct tree treenode;
typedef treenode *btree;
//插入结点
btree insertnode(btree root, int value)
{
btree newnode;
btree temp = root;
//记录父节点
btree back;
//创建新的结点
newnode = new treenode;
newnode->data = value;
newnode->left = NULL;
newnode->right = NULL;
if (root == NULL)
{
return newnode;
}
else
{
while (temp != NULL)
{
back = temp;
if (temp->data > value)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
if (back->data > value)
{
back->left = newnode;
}
else
{
back->right = newnode;
}
}
return root;
}
//二叉查找树的中序遍历
void Printtree(btree root)
{
if (root)
{
Printtree(root->left);
cout << root->data << " ";
Printtree(root->right);
}
}
//判断这棵树是否是平衡二叉树
bool isAVL(btree root, int &height)
{
if (root == NULL)
{
//空树
height = 0;
return true;
}
int heightLeft;
bool resultLeft = isAVL(root->left, heightLeft);
int heightRight;
bool resultRight = isAVL(root->right, heightRight);
//左子树和右子树都是AVL树,并且高度相差不大于1.返回真
if (resultLeft && resultRight && abs(heightLeft - heightRight) <= 1)
{
height = max(heightLeft, heightRight) + 1;
return true;
}
else
{
height = max(heightLeft, heightRight) + 1;
return false;
}
}
int main()
{
int height = 0;
btree root = NULL;
int data[MAX] = {5,4,6,3};
//循环插入,形成二叉排序树
for (int i = 0; i < MAX; i++)
{
root = insertnode(root, data[i]);
}
//中序遍历
Printtree(root);
cout << endl;
//如果该树是平衡二叉树则输出Yes
if (isAVL(root, height))
{
cout << "Yes" << endl;
}
else
{
cout << "NO" << endl;
}
return 0;
}