I'm writing a random tree and would like to track the height of the subtrees in the node. What method should this count be tracked in? Should this be a recursive call everytime a node is added?

## 6 Replies - 4255 Views - Last Post: 28 November 2008 - 03:33 PM

##
**Replies To:** Calculating tree height for random tree

### #2

## Re: Calculating tree height for random tree

Posted 28 November 2008 - 01:27 PM

Like so:

findHeight(BinaryTree aBinaryTree)

{

if (aTree.isEmpty())

return 0;

else

{

int heightLeft=height(aTree.getLeftSubtree());

int heightRight=height(aTree.getRightSubtree());

if (heightLeft >= heightRight)

return heightLeft+1;

else

return heightRight+1;

}

findHeight(BinaryTree aBinaryTree)

{

if (aTree.isEmpty())

return 0;

else

{

int heightLeft=height(aTree.getLeftSubtree());

int heightRight=height(aTree.getRightSubtree());

if (heightLeft >= heightRight)

return heightLeft+1;

else

return heightRight+1;

}

### #3

## Re: Calculating tree height for random tree

Posted 28 November 2008 - 01:31 PM

name edirol: date 28, Nov, 2008 12:31 pm

so i'll need a function findHeight that get calls everytime I add a node?

edirol

so i'll need a function findHeight that get calls everytime I add a node?

edirol

Sadaiy, on 28 Nov, 2008 - 12:27 PM, said:

Like so:

findHeight(BinaryTree aBinaryTree)

{

if (aTree.isEmpty())

return 0;

else

{

int heightLeft=height(aTree.getLeftSubtree());

int heightRight=height(aTree.getRightSubtree());

if (heightLeft >= heightRight)

return heightLeft+1;

else

return heightRight+1;

}

findHeight(BinaryTree aBinaryTree)

{

if (aTree.isEmpty())

return 0;

else

{

int heightLeft=height(aTree.getLeftSubtree());

int heightRight=height(aTree.getRightSubtree());

if (heightLeft >= heightRight)

return heightLeft+1;

else

return heightRight+1;

}

### #4

## Re: Calculating tree height for random tree

Posted 28 November 2008 - 02:50 PM

No, you create the tree first. Then when you want to find the height you run the findHeight function once(it is recursive).

### #5

## Re: Calculating tree height for random tree

Posted 28 November 2008 - 02:56 PM

### #6

### #7

## Re: Calculating tree height for random tree

Posted 28 November 2008 - 03:33 PM

Well, I don't know when you want to find the height.. Usually after the tree has been comepletely built (all nodes have been added), then you can find the height of it if you want too.

Page 1 of 1