基础版本:
int GetBinaryTreeDepth(BinaryTreeNode* pRoot)
{
if (nullptr == pRoot) return 0;
int leftTreeDepth = pRoot->pLeft != nullptr ? GetBinaryTreeDepth(pRoot->pLeft) : 0;
int rightTreeDepth = pRoot->pRight != nullptr ? GetBinaryTreeDepth(pRoot->pRight) : 0;
return (leftTreeDepth > rightTreeDepth) ? (leftTreeDepth + 1) : (rightTreeDepth + 1);
}
bool IsBalanceBinaryTree(BinaryTreeNode* pRoot)
{
if (NULL == pRoot) return true;
int leftTreeDepth = GetBinaryTreeDepth(pRoot->pRight);
int rightTreeDepth = GetBinaryTreeDepth(pRoot->pRight);
if (leftTreeDepth - rightTreeDepth > 1 || leftTreeDepth - rightTreeDepth < -1) return false;
return IsBalanceBinaryTree(pRoot->pLeft) && IsBalanceBinaryTree(pRoot->pRight);
}
改进版本:
bool IsBalanceBinaryTree(BinaryTreeNode* pRoot, int& depth)
{
if (NULL == pRoot)
{
depth = 0;
return true;
}
int leftTreeDepth = 0;
int rightTreeDepth = 0;
if (!IsBalanceBinaryTree(pRoot->pLeft, leftTreeDepth)) return false;
if (!IsBalanceBinaryTree(pRoot->pRight, rightTreeDepth)) return false;
if (leftTreeDepth - rightTreeDepth > 1 || leftTreeDepth - rightTreeDepth < -1) return false;
depth = 1 + (leftTreeDepth > rightTreeDepth ? leftTreeDepth : rightTreeDepth);
return true;
}
bool IsBalanceBinaryTree(BinaryTreeNode* pRoot)
{
if (nullptr == pRoot) return true;
int depth = 0;
return IsBalanceBinaryTree(pRoot, depth);
}
本文介绍了两种不同的算法实现方式来判断一棵二叉树是否为平衡二叉树,并计算其深度。基础版本直接递归计算左右子树深度,而改进版本在判断平衡的同时计算深度,避免了重复计算,提高了效率。

被折叠的 条评论
为什么被折叠?



