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.
基本思路:
判断二叉树是否平衡,判断其左右子树深度差距总不超过1.
引入一辅助函数,其返回树的深度。
同时,如果其发现自己左右子树已经不平稀,则返回-1。
/**
 * 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 helper(root) != -1;
    }
    
    int helper(TreeNode *root) {
        if (!root) return 0;
        const int left = helper(root->left);
        if (left == -1) 
            return left;
        const int right = helper(root->right);
        if (right == -1 || abs(left-right)>1) 
            return -1;
        return max(left, right) + 1;
    }
};Balanced Binary Tree -- leetcode
原文:http://blog.csdn.net/elton_xiao/article/details/45600141