The problem is not finding the depth, the problem is to do it just once. Here is the way to do it: do not create a function for finding a depth of the current node. Instead, include the depth of a current node as a parameter of the recursive function.
void AccumulateNodeInfo(
node * parent, uint parentDepth,
uint & accumulatedDepth, uint & nodeCount);
Initialize
accumulatedDepth
and
nodeCount
to 0 and call this function with the root node. The function should call the current node's children with
parentDepth + 1
, add
parentDepth
to
accumulatedDepth
and increment the
nodeCount
. After this function traverses all the tree,
accumulatedDepth
will be equal to sum of the depths and
nodeCount
equal to the node count.
—SA