Share my C++ solution using recursion


  • 0
    V
    class Solution {
    public:
        bool isBalanced(TreeNode* root) {
            if (root == NULL) return true;
            
            int l = getDepth(root->left);
            int r = getDepth(root->right);
            
            if (abs(l - r) > 1)
                return false;
                
            return isBalanced(root->left) && isBalanced(root->right);
        }
        
        int getDepth(TreeNode *root) {
            if (root == NULL) return 0;
            
            int ltree = 0, rtree = 0;
            ltree = getDepth(root->left);
            rtree = getDepth(root->right);
            
            if (ltree < rtree)
                ltree = rtree;
                
            return ltree + 1;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.