i get a stack error

template <class KT, class DT>
void my_bst<KT,DT>::show_bst_structure() const
{
	my_bst_node<KT,DT>* b=root;
	show_bst_structure(b,0);
}

template <class KT, class DT>
void my_bst<KT,DT>::show_bst_structure(my_bst_node<KT,DT>*& p, int level) const
{
	int i;
	if ( root == NULL ) 
	{
		for ( i = 0; i < level; i++ )
		{
			putchar ( '\t' );
			puts ( "~" );
		}
	}
	else
	{
		if(p->left!=NULL)
		{
			show_bst_structure(root->left, level + 1 );
			for ( i = 0; i < level; i++ )
			{
				putchar ( '\t' );
				printf ( "%d\n", root->data );
			}
		}
		else if(p->right!=NULL)
		{
			show_bst_structure( root->right, level + 1 );
			for ( i = 0; i < level; i++ )
			{
				putchar ( '\t' );
				printf ( "%d\n", root->data );
			}
		}
   }

}

Dani AI

Generated

Stack overflow here is almost certainly caused by infinite recursion. In the code posted by the routine checks the member root for NULL and recurses using root->left/root->right while the recursive parameter p is the node that should move through the tree. Because the class member root never changes the recursion never reaches a base case. Two other issues that make the routine behave incorrectly: the use of else if prevents visiting both children, and printf("%d", ...) is unsafe inside a templated class when DT is not an int.

What to change (concrete checklist):

  • Make the base case test the parameter pointer: check p == NULL, print the placeholder with the current indentation, then return.
  • Use the parameter p everywhere inside the recursive function (both for recursive calls and for printing the node value). Do not use the member root inside the recursion.
  • Recurse both subtrees (no else if) so both left and right are displayed.
  • Pass the node pointer by value (or const pointer) rather than as node*& unless you need to modify the caller’s pointer.
  • Print p->data with operator<< (or a type-safe formatter) instead of printf("%d", ...) to avoid type mismatches in templates.

Example (sideways tree print, right subtree first so the root appears leftmost):

template<class KT, class DT>
void my_bst<KT,DT>::show_bst_structure(my_bst_node<KT,DT>* p, int level) const {
    if (!p) {
        for (int i = 0; i < level; ++i) std::cout << '\t';
        std::cout << "~\n";
        return;
    }
    show_bst_structure(p->right, level + 1);
    for (int i = 0; i < level; ++i) std::cout << '\t';
    std::cout << p->data << '\n';
    show_bst_structure(p->left, level + 1);
}

If the original goal was breadth‑first (level‑order) traversal rather than a structural sideways print, use a queue-based approach (see general Tree traversal and std::queue for implementation details).

almost have it work!!!

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.