Hi all,

I wrote this recursive function to set the heights of each node in a search tree. It is not performing as expected; I suspect I screwed up the recursion somehow. Anyone know what the matter is?

void AVLTree::SetHeight(NodePtr &node) // root is passed in
{
	if(node == NULL)
	{
		return;
	}
	
	SetHeight(node->right); // start at bottom of left subtree

	node->rightHeight = GetHeight(node->right);
	
	if(node->rightHeight == -1)
	{
		node->rightHeight++;
	}

	node->leftHeight = GetHeight(node->left);

	if(node->leftHeight == -1)
	{
		node->leftHeight++;
	}

	SetHeight(node->left); 
}

Recommended Answers

All 2 Replies

It's hard to answer your question without knowing what GetHeight does.

You should be just setting the root height to 0 then set its left and right height to n+1. No need for get height function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.