Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding depth of Binary Tree 1

Status
Not open for further replies.

Seijuro

Programmer
Oct 8, 2003
10
US
I need help finding the depth of a binary tree. I want to run this after each insert and print out the depth. Any help would be appreciated. Can anyone give me some sample code that would do this or tell me how to do this??

 
In English, return the greater of the depths of your left and right subtrees + 1. An empty subtree has depth zero.

Yes, it's recursive.
 
... which means it may or may not be what you want. If your tree is being built evenly, then the depth shouldn't vary by more than one whatever branch you follow. In which case you can follow a single branch and get the answer to within one, without any recursion or large-scale searching (which will happen if you search the whole tree recursively).
If the tree is not being built evenly, then the recursive version tells you the deepest bit.

Remember that a single insert can only change the depth by one. If you modify your insert function you can make it return the depth of insert. Otherwise every time you do the insert you will search the entire tree.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top