Description:
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.
Analysis:
递归+二叉树先序遍历。
先求出左右子树高度,如果该根结点的子树是二叉平衡树,再依次判断左子树是否是二叉平衡树,最后判断右子树是否是二叉平衡树。
int getHeight(struct TreeNode *root) {
if (root == NULL)
return 0;
int left = getHeight(root->left);
int right = getHeight(root->right);
if (left > right)
return left + 1;
else
return right + 1;
}
bool isBalanced(struct TreeNode* root) {
if (root == NULL)
return true;
int left = getHeight(root->left);
int right = getHeight(root->right);
if ((left - right > 1) || (right - left > 1))
return false;
else
return(isBalanced(root->left) && isBalanced(root->right));
}