Simple C++ 9ms Solution Using Pair< >

  • 0
    bool isBalanced(TreeNode* root) {
            return getState(root).first;
        //function returns a pair containing the balanced state of the node and its height
        pair<bool, int> getState(TreeNode* root){
                return {true, 0};
            auto leftChildState = getState(root->left);
            auto rightChildState = getState(root->right);
            if(leftChildState.first && rightChildState.first){
                bool balancedState = abs(leftChildState.second - rightChildState.second) < 2;
                int height = max(leftChildState.second, rightChildState.second) + 1;
                return {balancedState, height};
            //if its not balanced, doesn't matter what height is returned as this would never be checked if state is false
            //so no need to spend extra time calculating height
            return {false, 0};

Log in to reply

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