Skip to content

Latest commit

 

History

History
42 lines (36 loc) · 952 Bytes

110. Balanced Binary Tree.md

File metadata and controls

42 lines (36 loc) · 952 Bytes
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if (!root) return true;
        int left = depth(root->left);
        int right = depth(root->right);
        return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }
    
    int depth(TreeNode* root) {
        if (!root) return 0;
        return max(depth(root->left), depth(root->right)) + 1;
    }
};
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if (!root) return true;
        bool balanced = true;
        height(root, balanced);
        return balanced;
    }
    
    int height(TreeNode* root, bool& balanced) {
        if (!root) return 0;
        int left = height(root->left, balanced);
        int right = height(root->right, balanced);
        if (abs(left - right) > 1) {
            balanced = false;
            return -1;
        }
        return max(left, right) + 1;
    }
};