题目:
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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3 / \ 9 20 / \ 15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1 / \ 2 2 / \ 3 3 / \ 4 4
Return false.
分析:
完全平衡二叉树的定义是任意两个节点高度之差小于等于1,根据这个定义,我们需要知道的是,因为需要求高度,如果任意两个子节点单独求,效率太差,因为有很多重复计算,我们想到是减少这种重复计算,这就需要从下往上算,
代码实现
class Solution {
public:
int _isBalanced(TreeNode* root)
{
if (root == NULL)
return 0;
int l = _isBalanced(root->left);
if (l == -1)
return -1;
int r = _isBalanced(root->right);
if (r == -1)
return -1;
if (abs(l - r) > 1)
return -1;
return max(l, r)+1;
}
bool isBalanced(TreeNode* root) {
return (_isBalanced(root)!=-1);
}
};