# counting depth and elements of a tree

This is a discussion on counting depth and elements of a tree within the C Programming forums, part of the General Programming Boards category; Uh hi, it's me again. I have another question. It's another one about binary search trees. I made one that ...

1. ## counting depth and elements of a tree

Uh hi, it's me again. I have another question.
It's another one about binary search trees.

I made one that works. I can tell that it works by traversing it in order. I've seen a lot of examples of traversing by recursion and that is what I used but I found that it's nearly impossible to count the number of levels and the number of elements on each level.

I tried to see if it was possible to count it in the recursive function but haven't really got anywhere.

Does anyone have a fresh approach to figuring this out?

2. wow, that's a pretty compact little recursive function
Would I be able to modify that code so it could count levels as well as the number of elements per level?

3. ok i have some code here that tells me how to find the depth
Code:
```int depth(NODE *node)
{
int left = -1;                    // clear left
int right = -1;                   // and right
if( node!= 0 )                // if the left child exists
left = depth(node->left);      // update the left depth
if( node!= 0 )               // if the right child exists
right = depth(node->right);    // update the right depth
if( left > right )               // if left is larger than
return left+1;             // right, return left + 1
return right+1;                // else return right + 1
}```
I have an array defined globally to keep track of how many words I find on each level. I don't know how to manipulate this code to store the numbers. Can anyone help?

Popular pages Recent additions