本文有两种方法判断一棵树是否为AVL树
#include <iostream>
#include<math.h> //abs
#include<queue>
#include <string>
using namespace std;
typedef struct TreeNode
{
string data;
struct TreeNode* lchild;
struct TreeNode* rchild;
}TreeNode;
void levelTraver(TreeNode* T) //层次遍历
{
if (!T)
return;
queue<TreeNode*> Q;
TreeNode* cur = T;
Q.push(cur);
while (!Q.empty())
{
cout << Q.front()->data << " ";
cur = Q.front();
Q.pop();
if (cur->lchild)
Q.push(cur->lchild);
if (cur->rchild)
Q.push(cur->rchild);
}
}
TreeNode* NodebyString(string s) //根据s的值
{
if (s == "#") //若str[i]的值为#,则不创建节点
return NULL;
else //否则,创建节点并返回
{
TreeNode* node = new TreeNode;
node->data = s;
return node;
}
}
TreeNode* levelDeSerialize(string str[]) //层序反序列化
{
int index1 = 0;
TreeNode* T = NodebyString(str[index1++]);
queue<TreeNode*> Q;
if (T != NULL)
Q.push(T);
TreeNode* cur;
while (!Q.empty())
{
cur = Q.front();
Q.pop();
cur->lchild = NodebyString(str[index1++]);
cur->rchild = NodebyString(str[index1++]);
if (cur->lchild)
Q.push(cur->lchild);
if (cur->rchild)
Q.push(cur->rchild);
}
return T;
}
int height(TreeNode* T) //求树的高度
{
if (!T)
return 0;
//后序遍历求树的高度
int LH = height(T->lchild);
int RH = height(T->rchild);
return (LH > RH) ? (1 + LH) : (1 + RH);
}
//方法一:
bool isAVLTree1(TreeNode* T) //是否为平衡二叉树
{
if (!T) //求以T为根的二叉树是否为AVL树
return true;
int LH = height(T->lchild); //求左子树的高度
int RH = height(T->rchild); //求右子树的高度
if (abs(LH - RH) > 1)
return false;
//再判断T的左子树和右子树是否为AVL树
return isAVLTree1(T->lchild) && isAVLTree1(T->rchild);
}
//方法二:
//二叉树的层序遍历,顺便记录每一个节点的高度depth、平衡性
bool isAVLTree2(TreeNode* T,int &depth) //传入的必须是引用
{
if (!T)
{
depth = 0;
return true;
}
int LH = 0;
int RH = 0;
if (isAVLTree2(T->lchild, LH) && isAVLTree2(T->rchild, RH))
{
if (abs(LH - RH) <= 1)
{
depth = 1 + (LH > RH ? LH : RH);
return true;
}
}
return false;
}
int main()
{
string str[] = { "1", "2", "3", "#", "4", "5", "#", "6", "#", "#", "#", "#","#" };
TreeNode* T = levelDeSerialize(str); //反序列化
cout << "层序遍历" << endl;
levelTraver(T);
cout << "\n高度 = ";
int H = height(T);
cout << H << endl;
int depth = 0;
bool isAVL = isAVLTree2(T, depth);
cout <<"是否为平衡二叉树"<<isAVL << endl;
return 0;
}
判断是否是平衡二叉树
最新推荐文章于 2021-10-10 10:27:54 发布