# depth of binary tree

This is a discussion on depth of binary tree within the C Programming forums, part of the General Programming Boards category; Code: int depth(cvor *root) { int left, right; if(root) { left = depth(root->left); right = depth(root->right); return 1 + (left ...

1. ## depth of binary tree

Code:
int depth(cvor *root)
{
int left, right;

if(root) {
left = depth(root->left);
right = depth(root->right);
return 1 + (left > right ? left : right);
}
return 0;
}
Can anyone help me understand this function?

I tried writing it down on paper but i just cant visualize how this works....

Should i try finding an animation of this on the internet and learning it like that? Or just write all calls to paper and try to understand how it works...

2. Since it's recursive, it may very well help you to draw out a tree on paper, and start at the bottom (since that way you won't have to build a freakishly large recursive thing). You'll see how it works pretty quickly that way, I reckon.

3. Looks like it always crawls down whichever is the larger of the two branches at any particular node. I'm not convinced it necessarily finds the longest path that way.

Plus if the left and right elements are node indexes or pointers (because that's what the recursive call depends on) I don't see a correlation between node pointer and geometrical depth.

4. Originally Posted by nonoob
Looks like it always crawls down whichever is the larger of the two branches at any particular node. I'm not convinced it necessarily finds the longest path that way.
I'm pretty sure it goes down both, what with there being two recursive calls. It passes the larger one up the chain, yes.

5. The height of a tree is equal to 1 plus the height of the left subtree or right subtree, whichever is greater. The height of an empty tree is zero.

If you can understand that, then great. That's exactly what the code says.