平衡二叉树

class Solution {
public:
    
    int isBalancedCore(TreeNode* root)
    {
        if(root == nullptr)
            return 0;
        int left = isBalancedCore(root -> left);
        if(left == -1)
            return -1;
        int right = isBalancedCore(root -> right);
        if(right == -1)
            return -1;            
        return (abs(left - right) > 1)? -1:  (left > right)? left+1: right+1;
    }
    bool isBalanced(TreeNode* root) {
        if(root == nullptr)
        {
            return true;
        }
        int height = 0;
        int res = isBalancedCore(root);
        if(res == -1)
            return false;
        else
            return true;
    }
};

 


版权声明:本文为longtao4012原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。