C
chandra.somesh
I recently was having trouble converting implementaion of recursions
using stack.
While single level of recursions are quite intuitive , it is when we
have more than one recursive calls in the function that the problem
arises.Consider for example a simple postorder traversal
void post(struct node * p)
{
if(p==NULL)
return;
post(p->left);
post(p->right);
cout<<p->info;
return;
}
if i try to implement the above code using stacks then this is how i
approach it.....
void post(sturct node *p)
{
do{
while(p!=NULL){
push(p);
p=p->left;
}
\\The above code signifies the first line of recursion
post(p->left);
p=pop(); \\Since p was null in previous step ,warranting the
pop in
the stack.
push(p); \\While this is to signify post(p->right);
p=p->right;
if(p==NULL)
{
p=pop();
cout<<p->info;
p=pop();
}
}while(!empty(queue));
}
Now the last few lines i really got confused and hence the resulting
code doesn't implement the correct logic.
Where am i going wrong?is there a thumb rule that one could follow in
order to implemnt recursions(of any level) using stacks.
Thanks in advance
Somesh
using stack.
While single level of recursions are quite intuitive , it is when we
have more than one recursive calls in the function that the problem
arises.Consider for example a simple postorder traversal
void post(struct node * p)
{
if(p==NULL)
return;
post(p->left);
post(p->right);
cout<<p->info;
return;
}
if i try to implement the above code using stacks then this is how i
approach it.....
void post(sturct node *p)
{
do{
while(p!=NULL){
push(p);
p=p->left;
}
\\The above code signifies the first line of recursion
post(p->left);
p=pop(); \\Since p was null in previous step ,warranting the
pop in
the stack.
push(p); \\While this is to signify post(p->right);
p=p->right;
if(p==NULL)
{
p=pop();
cout<<p->info;
p=pop();
}
}while(!empty(queue));
}
Now the last few lines i really got confused and hence the resulting
code doesn't implement the correct logic.
Where am i going wrong?is there a thumb rule that one could follow in
order to implemnt recursions(of any level) using stacks.
Thanks in advance
Somesh