Accepted solution using recursion and stack


  • 0
    J
    class Solution {
        stack<int> height;
    public:
        bool isBalanced(TreeNode* root) {
            if (!root)
            {
                height.push(0);
                return true;
            }
            if (!isBalanced(root->left)) return false;
            int leftH = height.top(); height.pop();
            if (!isBalanced(root->right)) return false;
            int rightH = height.top(); height.pop();
            if (abs(leftH - rightH) <= 1)
            {
                height.push(max(leftH, rightH)+1);
                return true;
            }
            else return false;
        }
    };

Log in to reply
 

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