A simple C++ solution using a depth-finding helper function


  • 2
    S

    Simple C++ solution that uses helper function depth:

    class Solution {
    public:
        /************************************************************//
        int depth(TreeNode* root){
            if (!root) return 0;                            //base case
            int left = depth(root->left) + 1;         //explore left
            int right = depth(root->right) + 1;    //explore right
    
            if (abs(left-right) > 1  ||  left < 1 || right < 1 ) { 
                return -1;
            }
    
            return (max(left,right));   
        }
        
       /************************************************************//
        bool isBalanced(TreeNode* root) {
            if (depth(root)<0) return false;
            return true;
        }
    };

Log in to reply
 

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