```
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){
if(!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};
}
```