Writing node counter for a BST recursively with pass by reference

How can I modify the code below so that it does not have a return type, but instead, uses a referenced variable? What I mean by this is that the function header is instead void countNodes(TreeNode *root, &nodeCount). I am just a bit confused on how to follow the recursion, that i'm not sure where to iterate the variable correctly to get the correct sum. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   int countNodes( TreeNode *root ) {
           // Count the nodes in the binary tree to which
           // root points, and return the answer.
        if ( root == NULL )
           return 0;  // The tree is empty.  It contains no nodes.
        else {
           int count = 1;   // Start by counting the root.
           count += countNodes(root->left);  // Add the number of nodes
                                            //     in the left subtree.
           count += countNodes(root->right); // Add the number of nodes
                                            //    in the right subtree.
           return count;  // Return the total.
        }
     } // end countNodes() 
Never mind. I think I figured it out. If I put a nodeCount++ after the two recursive calls to the function, it works!
The issue I am having is the same, but this time for a function determining the height of the tree. This is the recursive code:

int maxDepth(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);

/* use the larger one */
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
}
}

Can I pass a height by reference to do this same thing?
Topic archived. No new replies allowed.