平衡二叉树定义:
一棵二叉树树或者是颗空树,或者是具有下列性质的二叉树:它的左子树和右子树都是平衡二叉树,且左子树和右子树的深度之差的绝对值不超过1。
很容易用代码实现一棵平衡二叉树的判断:
class Solution {
public:
//判断函数
bool IsBalanced(TreeNode* pRoot) {
if (pRoot == NULL)
return true;
int deep_left = deep(pRoot->left);
int deep_right = deep(pRoot->right);
if (abs(deep_left - deep_right) > 1)
return false;
else
return IsBalanced(pRoot->left) && IsBalanced(pRoot->right);
}
int deep(TreeNode* p)//求深度函数
{
if(p == NULL)
return 0;
return 1 + (deep(p->left) > deep(p->right) ? deep(p->left) : deep(p->right));
}
};