Divide and conquer c++ version


  • 0
    S
    class Solution {
    public:
        vector<int> balancedHelper(TreeNode *root) {
            vector<int> rsVector = vector<int>();
            rsVector.push_back(1);
            rsVector.push_back(0);
            if (NULL == root) {
                return rsVector;
            }
            vector<int> leftVector = balancedHelper(root->left);
            vector<int> rightVector = balancedHelper(root->right);
            bool leftBalance = leftVector[0];
            int leftDepth = leftVector[1];
            bool rightBalance = rightVector[0];
            int rightDepth = rightVector[1];
            if (false == leftBalance || false == rightBalance || abs(leftDepth - rightDepth) >= 2) {
                rsVector[0] = 0;
                return rsVector;
            }
            rsVector[1] = (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1);
            return rsVector;
        }
        bool isBalanced(TreeNode* root) {
            vector<int> rsVector = balancedHelper(root);
            return rsVector[0];
        }
    };
    

Log in to reply
 

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