输入一棵二叉树,判断该二叉树是否是平衡二叉树。
class Solution {
public:
int depth(TreeNode* pRoot)
{
if(!pRoot)
return 0;
int left = depth(pRoot->left);
int right = depth(pRoot->right);
return (left > right ? left : right) + 1;
}
bool IsBalanced_Solution(TreeNode* pRoot)
{
if(!pRoot)
return true;
bool okL = IsBalanced_Solution(pRoot->left);
bool okR = IsBalanced_Solution(pRoot->right);
int lenL = depth(pRoot->left);
int lenR = depth(pRoot->right);
return (abs(lenL - lenR) <= 1) && okL && okR;
}
};