class Solution {
public:
//求深度
int deep(TreeNode* root)
{
if(root == NULL)
return 0;
//求左右子樹的深度
int left = deep(root->left);
int right = deep(root->right);
return (left > right) ? left+1 : right+1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
// write code here
//平衡二叉樹:左右子樹的深度不超過1
//也就是每個根節點的左右子樹的差都不超過1
//思路:先序遍歷,分別求根節點的左右子樹的深度,然後判斷是否超過1
if(pRoot == NULL)
return true;
//判斷根節點是否是平衡二叉樹
int left = deep(pRoot->left );
int right = deep(pRoot->right);
if(left - right > 1 || left - right < -1)
return false;
//判斷左右子樹是不是平衡二叉樹
return (IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right));
}
};