x
Solved

# Is is possible to convert the following code without using recursive way??

Posted on 2006-06-10
Medium Priority
264 Views
void level_order_aux ( node *tree, int level )
{
if ( tree == 0 )
return;

if ( level == 0 )
printf ( "%d ", tree->data );
else if ( level > 0 ) {
puts ( "Recurse left" );
level_order_aux ( tree->left, level - 1 );
puts ( "Recurse right" );
level_order_aux ( tree->right, level - 1 );
}
}

void level_order ( node *tree )
{
for ( int d = 0; d <= height ( tree ); d++ )
level_order_aux ( tree, d );
}
0
Question by:shingo43
1 Comment

LVL 22

Accepted Solution

grg99 earned 375 total points
ID: 16879298
Sure, but you'd need an auxiliary array to remember where you've been, so you can back up.  SOmething very rougly like:

node * save [ MaxLevels ];

p = 0;

Save[ p ] = tree;  // save our place
while( tree->left != NULL ) {
Save[ p++ ] = tree;  // save our place
printf( "%d",  tree->data );
tree = tree->left;
}

for( --p; p >= 0; p--) {  // now backtrack
tree = Save[ -- p ];
while( tree->right != NULL ) {
printf( "%d",  tree->data );
tree = tree->right;
}
}
--- make that VERY roughly!

The basic idea is to instead of recursing, make an entry in the save array.  Then backup thru the info.

0

## Featured Post

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.