Soooo Close- Interesting Question

I am having trouble tweaking my non-recursive preorder to print in a non-recursive preorder fashion. Any ideas?


Preorder recursive
1
2
3
4
5
6
7
8
9
10
11
   template< typename T >
   void BinaryTree<T>::preorder( BinaryTreeNode<T> * p )
   {
	   if (  p == NULL )  return  ;
	   else
	   {
		   cout <<  p->data   << "  ";
		   preorder( p->left );			   
		   preorder( p->right );
   }
   }
Last edited on
Any ideas? This is what I have so far but am getting an error
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
   template< typename T >
   void BinaryTree<T>::nr_preorder( BinaryTreeNode<T> * p )
   {
	   if (  p == NULL )  return ;
	   else
	   {
		   queue< BinaryTreeNode<T> >   que;
		   que.push( *root );
			   while ( !que.empty() )
		   {
			   BinaryTreeNode<T>  temp  =  que.front();
			   que.pop();
			   cout  <<  temp.data  << "  ";
			   if ( temp.left   !=  NULL )  que.push( * temp.left );	
			  
                            if ( temp.right  !=  NULL )  que.push( * temp.right);	
	   }
		   }
	   }



Error:
Error 1 error C2597: illegal reference to non-static member 'hgjhgj::BinaryTree<T>::root'

Last edited on
-
Last edited on
Trying a stack instead of a queue...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
	   
template< typename T >
   void BinaryTree<T>::nr_preorder( )
 	   {
	   if (  root == NULL )  return ;
	   else
	   {
		   stack< BinaryTreeNode<T> >   que;
		   que.push( *root );
			   while ( !que.empty() )
		   {
			   BinaryTreeNode<T>  temp;
			   que.push(root);
			   cout  <<  temp.data  << "  ";
			   if ( temp.left   !=  NULL )  que.push( * temp.left );	
			   if ( temp.right  !=  NULL )  que.push( * temp.right ;	  
			   }
		   }
	   }


getting error:

Error 1 error C2664: 'void std::stack<_Ty>::push(fghfh::BinaryTreeNode<T> &&)' : cannot convert parameter 1 from 'fghfh::BinaryTreeNode<T> *' to 'fghfh::BinaryTreeNode<T>

Last edited on
Again I am trying to print the nodes of a binary tree - preorder - using a stack.
Last edited on
Is the forum stumped!?
To do preorder using a stack, you should push the right child then the left child.

Your last compiler error is happening because on line 13, you're doing:

que.push(root);

where root is a BinaryTreeNode<T>* (pointer) whereas que is a stack of BinaryTreeNode<T> (not pointers). I would make it a stack of pointers to BinaryTreeNodes to avoid copying on push.
Fixed that part but Im still not at a viable solution...
Last edited on
Hmmmm
Topic archived. No new replies allowed.