Mar 23, 2012 at 5:44pm UTC
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 Mar 26, 2012 at 1:06am UTC
Mar 23, 2012 at 7:19pm UTC
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 Mar 23, 2012 at 7:39pm UTC
Mar 23, 2012 at 7:51pm UTC
-
Last edited on Mar 23, 2012 at 9:44pm UTC
Mar 23, 2012 at 8:49pm UTC
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 Mar 23, 2012 at 8:50pm UTC
Mar 23, 2012 at 9:28pm UTC
Again I am trying to print the nodes of a binary tree - preorder - using a stack.
Last edited on Mar 23, 2012 at 9:29pm UTC
Mar 23, 2012 at 10:11pm UTC
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.
Mar 26, 2012 at 12:55am UTC
Fixed that part but Im still not at a viable solution...
Last edited on Mar 26, 2012 at 1:25am UTC