#include "iostream"
using namespace std;
struct BinaryTreeNode{
int data;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
int TreeDeep(BinaryTreeNode *pRoot)
{
if (pRoot == NULL)
return 0;
int nLeft = TreeDeep(pRoot->left);
int nRight = TreeDeep(pRoot->right);
return nLeft > nRight ? (nLeft + 1 ): (nRight + 1);
}
bool IsBalanced(BinaryTreeNode* pRoot, int* pDepth)
{
if (pRoot==NULL)
{
*pDepth = 0;
return true;
}
int left, right;
if (IsBalanced(pRoot->left,&left)&&IsBalanced(pRoot->right,&right))
{
int diff = left - right;
if (diff<=1&&diff>=-1)
{
*pDepth = 1 + (left > right ? left : right);
return true;
}
}
return false;
}
bool IsBalanced(BinaryTreeNode *pRoot)
{
int depth = 0;
return IsBalanced(pRoot, &depth);
}
int main()
{
system("pause");
return 0;
}剑指offer面试题39:二叉树深度以及判断平衡二叉树
最新推荐文章于 2026-04-02 07:49:17 发布
本文介绍了一种用于判断二叉树是否为平衡二叉树的算法,并提供了完整的C++实现代码。通过递归计算二叉树的深度,判断每个子树是否平衡,最终确定整棵树是否满足平衡条件。

528

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



