calculate the height of binary tree with a given node

Hi, how to write a recursive function that takes as input a pointer to the root of the tree and a node, and returns the height of the tree or subtree having the node with the given node as its root.
closed account (D80DSL3A)
That was an interesting problem. I came up with a method which appears to work.
Here's an outline:

Let the start node be pNode, then (in main):
1
2
3
int hMax = 0;
tree.climb(pNode, 0, hMax);
cout << "height of tree = " << hMax;

Where (in the tree class):
int climb(BinNode* pNode, int h, int& hMax);

1) Within the climb function climb to a local treetop from the starting node.
1
2
3
4
5
// climb as high as possible
if( pNode->pLeft )	
	h = climb( pNode->pLeft, h+1, hMax );// recursive call
if( pNode->pRight )	
	h = climb( pNode->pRight, h+1, hMax );	

2) When you have reached a top, note your height:
1
2
if( h > hMax )
	hMax = h;

3) Then climb back down
return h-1;// climb back down

I'd give the function outright but we're not supposed to give solutions to homework problems here. Hope this helps (and that it actually works under rigorously testing!)
Topic archived. No new replies allowed.