Inorder Tree Traversal Without Recursion - GeeksforGeeks PDF
Inorder Tree Traversal Without Recursion - GeeksforGeeks PDF
Inorder Tree Traversal Without Recursion - GeeksforGeeks PDF
InorderTreeTraversalwithoutRecursionGeeksforGeeks
InorderTreeTraversalwithout
Recursion
UsingStackistheobviouswaytotraversetreewithoutrecursion.Belowisanalgorithmfortraversing
binarytreeusingstack.Seethisforstepwisestepexecutionofthealgorithm.
1)CreateanemptystackS.
2)Initializecurrentnodeasroot
3)PushthecurrentnodetoSandsetcurrent=current>leftuntilcurrentisNULL
4)IfcurrentisNULLandstackisnotemptythen
a)Popthetopitemfromstack.
b)Printthepoppeditem,setcurrent=popped_item>right
c)Gotostep3.
5)IfcurrentisNULLandstackisemptythenwearedone.
Letusconsiderthebelowtreeforexample
1
/\
23
/\
45
Step1Createsanemptystack:S=NULL
Step2setscurrentasaddressofroot:current>1
Step3Pushesthecurrentnodeandsetcurrent=current>leftuntilcurrentisNULL
current>1
push1:StackS>1
current>2
push2:StackS>2,1
current>4
push4:StackS>4,2,1
current=NULL
Step4popsfromS
a)Pop4:StackS>2,1
b)print"4"
c)current=NULL/*rightof4*/andgotostep3
SincecurrentisNULLstep3doesn'tdoanything.
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%
1/5
5/21/2015
InorderTreeTraversalwithoutRecursionGeeksforGeeks
Step4popsagain.
a)Pop2:StackS>1
b)print"2"
c)current>5/*rightof2*/andgotostep3
Step3pushes5tostackandmakescurrentNULL
StackS>5,1
current=NULL
Step4popsfromS
a)Pop5:StackS>1
b)print"5"
c)current=NULL/*rightof5*/andgotostep3
SincecurrentisNULLstep3doesn'tdoanything
Step4popsagain.
a)Pop1:StackS>NULL
b)print"1"
c)current>3/*rightof5*/
Step3pushes3tostackandmakescurrentNULL
StackS>3
current=NULL
Step4popsfromS
a)Pop3:StackS>NULL
b)print"3"
c)current=NULL/*rightof3*/
TraversalisdonenowasstackSisemptyandcurrentisNULL.
Implementation:
#include<stdio.h>
#include<stdlib.h>
#defineboolint
/*AbinarytreetNodehasdata,pointertoleftchild
andapointertorightchild*/
structtNode
{
intdata;
structtNode*left;
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%
2/5
5/21/2015
InorderTreeTraversalwithoutRecursionGeeksforGeeks
structtNode*right;
};
/*Structureofastacknode.LinkedListimplementationisusedfor
stack.Astacknodecontainsapointertotreenodeandapointerto
nextstacknode*/
structsNode
{
structtNode*t;
structsNode*next;
};
/*Stackrelatedfunctions*/
voidpush(structsNode**top_ref,structtNode*t);
structtNode*pop(structsNode**top_ref);
boolisEmpty(structsNode*top);
/*Iterativefunctionforinordertreetraversal*/
voidinOrder(structtNode*root)
{
/*setcurrenttorootofbinarytree*/
structtNode*current=root;
structsNode*s=NULL;/*Initializestacks*/
booldone=0;
while(!done)
{
/*ReachtheleftmosttNodeofthecurrenttNode*/
if(current!=NULL)
{
/*placepointertoatreenodeonthestackbeforetraversing
thenode'sleftsubtree*/
push(&s,current);
current=current>left;
}
/*backtrackfromtheemptysubtreeandvisitthetNode
atthetopofthestack;however,ifthestackisempty,
youaredone*/
else
{
if(!isEmpty(s))
{
current=pop(&s);
printf("%d",current>data);
/*wehavevisitedthenodeanditsleftsubtree.
Now,it'srightsubtree'sturn*/
current=current>right;
}
else
done=1;
}
}/*endofwhile*/
}
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%
3/5
5/21/2015
InorderTreeTraversalwithoutRecursionGeeksforGeeks
/*UTILITYFUNCTIONS*/
/*FunctiontopushanitemtosNode*/
voidpush(structsNode**top_ref,structtNode*t)
{
/*allocatetNode*/
structsNode*new_tNode=
(structsNode*)malloc(sizeof(structsNode));
if(new_tNode==NULL)
{
printf("StackOverflow\n");
getchar();
exit(0);
}
/*putinthedata*/
new_tNode>t=t;
/*linktheoldlistoffthenewtNode*/
new_tNode>next=(*top_ref);
/*movetheheadtopointtothenewtNode*/
(*top_ref)=new_tNode;
}
/*Thefunctionreturnstrueifstackisempty,otherwisefalse*/
boolisEmpty(structsNode*top)
{
return(top==NULL)?1:0;
}
/*Functiontopopanitemfromstack*/
structtNode*pop(structsNode**top_ref)
{
structtNode*res;
structsNode*top;
/*IfsNodeisemptythenerror*/
if(isEmpty(*top_ref))
{
printf("StackUnderflow\n");
getchar();
exit(0);
}
else
{
top=*top_ref;
res=top>t;
*top_ref=top>next;
free(top);
returnres;
}
}
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%
4/5
5/21/2015
InorderTreeTraversalwithoutRecursionGeeksforGeeks
/*HelperfunctionthatallocatesanewtNodewiththe
givendataandNULLleftandrightpointers.*/
structtNode*newtNode(intdata)
{
structtNode*tNode=(structtNode*)
malloc(sizeof(structtNode));
tNode>data=data;
tNode>left=NULL;
tNode>right=NULL;
return(tNode);
}
/*Driverprogramtotestabovefunctions*/
intmain()
{
/*Constructedbinarytreeis
1
/\
23
/\
45
*/
structtNode*root=newtNode(1);
root>left=newtNode(2);
root>right=newtNode(3);
root>left>left=newtNode(4);
root>left>right=newtNode(5);
inOrder(root);
getchar();
return0;
}
TimeComplexity:O(n)
References:
http://web.cs.wpi.edu/~cs2005/common/iterative.inorder
http://neural.cs.nthu.edu.tw/jang/courses/cs2351/slide/animation/Iterative%20Inorder%20Traversal.pps
SeethispostforanotherapproachofInorderTreeTraversalwithoutrecursionandwithoutstack!
Pleasewritecommentsifyoufindanybuginabovecode/algorithm,orwanttosharemore
informationaboutstackbasedInorderTreeTraversal
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%
5/5