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.
思路:height-balanced tree 是平衡二叉树,又称AVL树。它或者是一棵空树,或者是具有下列性质的二叉树:它的左子树和右子树都是二叉树,且左子树和右子树的深度之差的绝对值不超过1。即,深度差值只能去-1,0,1。
因此,对于每个结点,先求它左子树及右子树的深度值。如果左、右子树深度差值符合要求,继续判断它的左子树和右子树是否为平衡二叉树,否则就不是平衡二叉树。
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
bool isBalanced(TreeNode *root)
{
if(!root)
return true;
else
if(judge(maxDepth(root->left), maxDepth(root->right)))//判断当前结点的左右子树深度差值是否符合要求
return isBalanced(root->left) && isBalanced(root->right);//继续判断它的左子树和右子树
else
return false;
}
bool judge(int L, int R)//左右子树深度差值的要求
{
if(L-R==0 || L-R==1 || L-R==-1)
return true;
else
return false;
}
int maxDepth(struct TreeNode *root)//以root为根的树的深度
{
if(root == NULL)
return 0;
else
{
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return (l > r ? l : r) + 1;
}
}
};