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



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