i believe that it checks every nodes height and makes sure that the left -right is 1 or 0 or -1. It is supposed to return tree if tree is balanced which means that left-right is 0 or 1 or -1 at every node.

template <class KT, class DT>
void my_bst<KT,DT>::balanced()
{
	if(balanced(root)==1)
	{
		cout<<"true\n";
	}
	else
	{
		cout<<"false\n";
	}
}

template <class KT, class DT>
bool my_bst<KT,DT>::balanced(my_bst_node<KT,DT>*& j)
{
	if((height(j->left)-height(j->right)==-1)||(height(j->left)-height(j->right)==1)||(height(j->left)-height(j->right)==0))
	{
		return true;
	}
	else
	{
		return false;
	}
	if(balanced(j->left)&&balanced(j->right))
	{
		if(j->left==NULL)
		{
			balanced(j->right);
		}
		else if(j->right==NULL)
		{
			balanced(j->left);
		}
	}
	else
	{
		return false;
	}
}

Recommended Answers

All 4 Replies

when do u suppose the control is coming to line #25?

i mean when the left and right tree is balanced. So returns true.

The previous posters point was that you have an IF statement on line 17...

an if is either true or false...

The 'true' clause has a return on line 19 and the 'false' clause has a return on line 23...

So in either case, the function has returned before you ever get to line 25.

There is also a lot of risk in the code as you have it written. The test on line 27 (and the related test on line 31) seem to imply that the left or right pointer could be NULL. But you have referenced the left and right pointer before the test. Based on the way you have written balanced() that would seem to be an inappropriate thing to be passing around.

i got it works thanks for help!

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.