题解 | #平衡二叉树#
平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int leftDeepth = 0;
int rightDeepth = 0;
//空树直接返回true
if(pRoot == nullptr) return true;
//左子树不为空时,判断左子树是否为平衡树,若是平衡树求该子树深度,否则为空
if(pRoot->left != nullptr){
if( IsBalanced_Solution(pRoot->left) )
{
leftDeepth = treeDeepth(pRoot->left);
}else return false;
}
//右子树不为空时,判断右子树是否为平衡树,若是平衡树求该子树深度,否则为空
if(pRoot->right != nullptr){
if(IsBalanced_Solution(pRoot->right))
{
rightDeepth = treeDeepth(pRoot->right);
}else return false;
}
//判断左右子树高度差是否小于等于1
if(abs(leftDeepth - rightDeepth)<=1) return true;
else return false;
}
//树的深度
int treeDeepth(TreeNode * pRoot)
{
if(pRoot == nullptr) return 0;
return ( treeDeepth(pRoot->left) > treeDeepth(pRoot->right)?
treeDeepth(pRoot->left) : treeDeepth(pRoot->right) ) + 1;
}
};