C++判斷一棵樹是不是平衡二叉樹(AVL樹)

  1. 首先要知道什麼是平衡二叉樹。
    節點左子樹和右子樹的高度差不超過1的數叫平衡二叉樹。
    應用場景:1.爲了避免樹的高度增長過快而影響二叉排序樹的性能

  2. 樹的高度:從根節點到葉子節點依次經過的節點形成的路徑,最長路徑的長度值爲樹的高度。

#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;
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章