LeetCode-110. 平衡二叉树
难度:简单
 110. 平衡二叉树
 给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
class Solution {
public:
    /*
        比较每个节点左右的高度差,所以需要从下往上遍历(后序遍历)
    */
    int getDepth(TreeNode* root){
        if(!root)return 0;
        
        int leftDepth = getDepth(root->left);
        if(leftDepth==-1)return -1;
        int rightDepth = getDepth(root->right);
        if(rightDepth==-1)return -1;
        if(abs(leftDepth-rightDepth)>1)return -1;
        return 1+max(leftDepth,rightDepth);
    }
    bool isBalanced(TreeNode* root) {
        int is = getDepth(root);
        return is>-1?true:false;
    }
};
执行用时:
 8 ms, 在所有 C++ 提交中击败了87.16%的用户
 内存消耗:
 20.5 MB, 在所有 C++ 提交中击败了26.09%的用户
 通过测试用例:
 228 / 228










