地址:http://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 ofevery node never differ by more than 1.
思路:如果根结点为NULL,返回true。否则分别递归求左右子树高度,判断左右子树高度是否差异大于1.
参考代码:
SECOND TRIAL
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int getHeight(TreeNode* root)
{
if(!root)
return 0;
return 1 + max(getHeight(root->left), getHeight(root->right));
}
public:
bool isBalanced(TreeNode *root) {
if(!root)
return true;
int lh = getHeight(root->left);
int rh = getHeight(root->right);
return abs(lh-rh)<=1 && isBalanced(root->left) && isBalanced(root->right);
}
};