Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 259
  • Last Modified:

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

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
shingo43
Asked:
shingo43
1 Solution
 
grg99Commented:
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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now