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;
	}
}

Edited 7 Years Ago by lotrsimp12345: n/a

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

Edited 7 Years Ago by lotrsimp12345: n/a

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.

This question has already been answered. Start a new discussion instead.