Is this efficient? I do not like the plain recursion part. But can't think of another better way.


  • 0
    V

    My solution using simple recursion.

    class Solution {
        public:
        
        int max(int a,int b){
            return (a>b)?a:b;
        }
            int depth(TreeNode *root){
        if(!root){return 0;}
        return 1+max(depth(root->left), depth(root->right));
        }
        
        int mod(int a){
            if(a<0){return -1*a;
            }
            return a;
        }
        
            bool isBalanced(TreeNode *root) {
                if(!root){return true;}
                return (isBalanced(root->left)&&isBalanced(root->right)) &&( (mod(depth(root->left)-depth(root->right)))<=1?true:false);
            }
        };

Log in to reply
 

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