题目链接
题目要求:
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.
这道题难度还好。具体程序(16ms)如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
return isBalancedSub(root);
} bool isBalancedSub(TreeNode *tree)
{
if(!tree)
return true;
if(abs(getHeight(tree->left) - getHeight(tree->right)) > )
return false;
return isBalancedSub(tree->left) && isBalancedSub(tree->right);
} int getHeight(TreeNode *tree)
{
if(!tree)
return ; int m = getHeight(tree->left);
int n = getHeight(tree->right);
return (m > n) ? m + : n + ;
}
};