Home > Back-end >  Non-recursive algorithm of traversing binary tree
Non-recursive algorithm of traversing binary tree

Time:09-23

Any big help kangkang where this code is not ah, why couldn't run the non-recursive algorithm results
#include
#include
# define MAX_NODE 50
# define STACKINITSIZE 20
# define INCREASEMENT 10
# define the ERROR 0
# define OK 1
Typedef int ElemType;

Typedef struct BTNode {
Char data;
Struct Lchild BTNode * and * Rchild;
} BTNode, * BTree; ;
BTNode * Create_BTree (void) {
BTNode * T, * p, * s [MAX_NODE];
Char ch;
Int I, j;

While (1) {
The scanf (" % d ", & amp; I);
If (I==0)
Break;
The else
{
Ch=getchar ();
P=(BTNode *) malloc (sizeof (BTNode));
P - & gt; data=https://bbs.csdn.net/topics/ch;
P - & gt; Lchild=p - & gt; Rchild=NULL;
S [I]=p;
If (I==1)
T=p;
The else {
J=I/2;
If (I % 2==0)
S [j] - & gt; Lchild=p;
The else
S [j] - & gt; Rchild=p;
}
}
}
Return (T);
}
Void RInorderTraverse BTNode * (T)
{
If (T==NULL)
return;
The else {
RInorderTraverse (T - & gt; Lchild);
Printf (" % c ", T - & gt; The data);
RInorderTraverse (T - & gt; Rchild);
}

}
Typedef struct SqStack
{
BTNode * base;
BTNode * top;
int stacksize;
} SqStack;
Int InitStack (SqStack & amp; S)
{
S.b ase=(BTNode *) malloc (STACKINITSIZE * sizeof (BTNode));
if(! S.b ase)
return 0;
S.t op=S.b ase;
S.s tacksize=STACKINITSIZE;
return 1;
}
Int a Push (SqStack & amp; S, BTNode e)
{
If (S.t op - S.b ase & gt;=S.s tacksize)
{
S.b ase=(BTNode *) realloc (S.b ase, sizeof (STACKINITSIZE + INCREASEMENT) * (BTNode));
if(! S.b ase)
return 0;
S.s tacksize=30;
}
* S.t op=e;
S.t op + +;
return 1;
}
Int Pop (SqStack & amp; S, BTNode & amp; E)
{
If (S.b ase==S.t op)
return 0;
S.t op -;
E=* S.t op;
return 1;
}
Int StackEmpty (SqStack S)
{
If (S.b ase==S.t op)
return 1;
The else
return 0;
}

Int NRInorderTraverse (BTree T)
{
SqStack s;
InitStack (s);
BTree p=T;
BTNode e;
while(! P | |! StackEmpty (s))
{
If (p)
{
Push (s, p);
P=p - & gt; Lchild;

}

The else
{
Pop (s, e);
Printf (" % d ", e.d ata);
P="e.R child;
}
}
printf("\n");
return 1;
}


Int main () {
BTree T=NULL;
Printf (" please enter the binary tree \ n ");
T=Create_BTree ();
Printf (" recursive algorithm sequence traversal of binary tree results as follows: \ n ");
RInorderTraverse (T);
printf("\n");
Printf (" non-recursive algorithm of traversing binary tree of sequence results as follows: \ n ");
NRInorderTraverse (T);
return 0;
}
  • Related