Solved

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

Posted on 2006-06-10
1
213 Views
Last Modified: 2012-05-05
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
Comment
Question by:shingo43
1 Comment
 
LVL 22

Accepted Solution

by:
grg99 earned 125 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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now