题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
int TreeDepth(struct TreeNode *p)
{
if (!p)
return 0;
int LD, RD;
LD = TreeDepth(p->left);
RD = TreeDepth(p->right);
return (LD > RD ? LD : RD) + 1;
}
//递归 满足平衡二叉树 且左右子树都是平衡二叉树
bool IsBalanced_Solution(struct TreeNode *pRoot)
{
if (!pRoot)
return true;
int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);
if (abs(left - right) > 1)
return false;
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}