C++ Recursive Solution


  • 0
    Y

    Define another method to calculate depth of tree.

    class Solution {
    public:

    int depth(TreeNode* root) {
        
        if (root == NULL) {
            return 0;
        }
        if (root->left == NULL && root->right == NULL) {
            return 1;
        }
        return max(depth(root->left), depth(root->right))+1;
        
    }
    
    bool isBalanced(TreeNode* root) {
        
        if (root == NULL) {
            return true;
        }
        
        return isBalanced(root->left) && isBalanced(root->right) && abs(depth(root->left)-depth(root->right))<=1;
        
    }
    

    };


Log in to reply
 

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