问题描述:
https://oj.leetcode.com/problems/balanced-binary-tree/点击打开链接
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.
示例代码:
/**
* Definition for binary tree
* 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;
int lh = height(root->left);
int rh = height(root->right);
int diff = lh > rh ? lh - rh : rh - lh;
if (diff > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int height(TreeNode *root)
{
if (!root) return 0;
int lh = height(root->left);
int rh = height(root->right);
return lh > rh ? lh + 1 : rh + 1;
}
};
该题有可以优化的地方:做了不必要的递归,计算高度和左右子树的判定能否合并??