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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

BTR Depth

Status
Not open for further replies.

ogito

Programmer
Nov 14, 2003
4
US
I need to write a routine that computes the maximum depth of the tree and run it after each insert and print out the depth. I've tried writing the code but it doesn't print out the depth! Can anyone help??

Code:
node *insert(int value, node *n) 
{
  if (n == NULL) 
  {
    return mkleaf(value) ; 
  } 
  if (value <= n -> contents )
  {
    n -> left = insert(value, n -> left) ; 
  }
  else 
  {
    n -> right = insert(value, n -> right) ; 
  }
  return n ; 
} 

int printnode(node *n)
{
  printf(&quot;node at %p value=%d left=%p right=%p\n&quot;, n, n -> contents, n -> left, n -> right) ; 
} 

node *mknode(int value, node *left, node *right)
{
   node *res = (node *)malloc(sizeof (node)) ; 
   res -> contents = value ; 
   res -> left = left ; 
   res -> right = right ; 
   return res ; 
} 

node *mkleaf(int value) 
{
  return mknode (value, NULL, NULL) ; 
} 

int preorder(node *n)
{
  if (n == NULL) return ; 
  preorder (n -> left) ; 
  printf (&quot;%d &quot;, n -> contents) ; 
  preorder (n -> right) ; 
}
 
nor do I. But if you have just inserted a (single) node into the tree, the most extra depth you can have added to the tree is 1. Therefore rather than searching the entire tree to find the deepest branch after inserting a node, the better approach is to detect whether you had to go to the greatest current depth of the tree to insert your node, and if so, add one to the greatest current depth. This avoids traversing the entire tree (and if you're going to traverse the entire tree, you might as well forget binary trees anyway. Their whole point is as a data structure that allows you to arrive somewhere without all that trouble! By the way, this problem crops up here very regularly. I wonder if it's in someone's course.)
 
This is what I have so far for depth

Code:
int depth( node * n )
{
  int r, l; /* right and left count */

  /* early-out if empty */
    if( n==0 )
    {
      /* tree is empty */
      return 0;
    }

  /* initialize to zero */
    r=l=0;

  /* count max in both directions */
    if( n->right )
    r=depth(n->right);

    if( n->left )
    l=depth(n->right);

  /* get higher count; store in r */
    if( l > r )
    r=l;

  /* return the depth of largest child + this node */
    return r+1;
}
 
... but remember this small piece of code hides a very large amount of tree-searching!
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top