本题源自LeetCode
-----------------------------------------------------------------------------
递归判断,用树的深度函数。判断左右子树的高度相差是否小于1,在递归判断左右子树是否为平衡二叉树。
bool isBalanced(TreeNode *root) {
if(root==NULL)
return true;
int left=depth(root->left);
int right=depth(root->right);
if(abs(left-right)<=1)
if(isBalanced(root->left)&&isBalanced(root->right)) //递归判断左右子树 是否是平衡树
return true;
return false;
}
int depth(TreeNode* root){
if(root==NULL)
return 0;
if(root->left==NULL&&root->right==NULL)
return 1;
return max(depth(root->left),depth(root->right))+1;
}