It's unclear why you're counting nodes when the definition of a balanced tree is right in front of you – in terms of height, not number of nodes.
The tricky part is that if you compute the depth and check for balance separately, you're going to end up with too great a complexity (O(n^2), I think).
So you need a helper function that computes both as it traverses the tree.
This is a pretty straightforward solution:
// Returns whether 'root' is a balanced tree.
// Also stores the tree's height in *height.
bool balanced_height(node* root, int* height)
{
// The trivial base case – an empty tree is balanced and has height 0.
if (root == nullptr)
{
*height = 0;
return true;
}
// Information gathering using recursion:
// Find out whether the subtrees are balanced, and get their heights.
int leftheight = 0;
int rightheight = 0;
bool leftbalance = balanced_height(root->left, &leftheight);
bool rightbalance = balanced_height(root->right, &rightheight);
// Now that we know the heights of the subtrees, we can store the height of this tree.
*height = max(leftheight, rightheight) + 1;
// Finally, a translation into C++ of the definition:
// A tree is balanced if and only if
// - the subtrees are balanced, and
// - the heights of the subtrees differ by at most one.
return leftbalance && rightbalance && abs(leftheight - rightheight) <= 1;
}
bool balanced(node* root)
{
int height = 0;
return balanced_height(root, &height);
}
It can be made slightly faster (but with the same complexity) in the unbalanced case by not traversing the second subtree if the first is unbalanced, since we're not going to use the height for anything in that case.
That optimisation is left as an exercise.