Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
判断给定的二叉树是否为平衡二叉树
思路:因为平衡二叉树要求左右子树的深度差值不超过1
这里先实现一个辅助函数,计算二叉树的深度;
最后采用递归的思想来完成;
class Solution {
public:
bool isBalanced(TreeNode* root)
{
if (root==NULL)
{
return true;
}
int left = help(root->left);
int right = help(root->right);
if (left-right>=-1 && left-right<=1)
{
if (isBalanced(root->left) && isBalanced(root->right))
{
return true;
}
}
return false;
}
int help(TreeNode* root)
{
if (root==NULL)
{
return 0;
}
if (root->left==NULL && root->right==NULL)
{
return 1;
}
return max(help(root->left), help(root->right)) + 1;
}
};