-
首先要知道什麼是平衡二叉樹。
節點左子樹和右子樹的高度差不超過1的數叫平衡二叉樹。
應用場景:1.爲了避免樹的高度增長過快而影響二叉排序樹的性能 -
樹的高度:從根節點到葉子節點依次經過的節點形成的路徑,最長路徑的長度值爲樹的高度。
#include<iostream>
int getTreeHeight(BiTree* tree);//聲明獲取樹高度的函數
//先寫一個樹結構
typedef struct Node
{
int data;
Node* lchild;
Node* rchild;
}BiTree;
//
bool isBalanced(BiTree* T)
{
if(!T) //空樹是平衡二叉樹
{
return true;
}
const int leftHeight = getTreeHeight(T->lchild); //求左右子樹的高度
const int rightHeight = getTreeHeight(T->rchild);
if(std::abs(leftHeight - rightHeight) > 1) //判斷根節點平衡因子不爲-1、0、1時
{
return false;
}
return (isBalanced(T->lchild) && isBalanced(T->rchild)); //遞歸調用,左右子樹都爲平衡二叉樹
}
//求樹的高度/深度,
int getTreeHeight(BiTree* tree)
{
if(!tree) //空樹
{
return 0;
}
else
{
int left = getTreeHeight(tree->lchild) + 1;
int right = getTreeHeight(tree->rchild) + 1;
return left > right ? left : right;
}
}