判斷是否是平衡二叉樹
阿新 • • 發佈:2018-10-31
本文有兩種方法判斷一棵樹是否為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;
}