Current location - Training Enrollment Network - Books and materials - C language algorithm for sequential storage based on preorder sequence and middle sequence.
C language algorithm for sequential storage based on preorder sequence and middle sequence.
Write a code, you try.

# include & ltstdio.h & gt

# include & ltstring.h & gt

# Define MAXSIZE 127

bool fun(char *Pre,char *Indor,char *Seq,int n,int R)

{

int i,root

If (n < = 0)

Returns1;

for(root = 0; (root & ltn)& amp; & amp(Indor[root]! = Pre[0]); root++);

if(root & gt; = n)

Returns 0;

seq[R]= Pre[0];

for(I = 0; I & ltr;; i++)

If (sequence [i] == 0)

seq[I]=“0”;

bool b 1 = fun(Pre + 1,Indor,Seq,root,2 * R+ 1);

bool b2 = fun(Pre + 1 + root,Indor + root + 1,Seq,n - root - 1,2 * R+2);

Return b1&; & ampB2;

}

int main(void)

{

char Pre[20],Indor[20],Seq[MAXSIZE],n,I;

bool bCreatOk

Printf ("Please enter a leading sequence: \ n");

scanf("%s ",Pre);

Printf ("Please enter intermediate sequence: \ n");

scanf("%s ",Indor);

n = strlen(Pre);

for(I = 0; I & ltMAXSIZEi++)

seq[I]= 0;

bCreatOk = fun(Pre,Indor,Seq,n,0);

If (b creates) {

Printf ("Binary tree constructed successfully! Its sequence binary tree is: \ n ");

for(I = 0; Sequence [I]; i++)

printf("%3c ",Seq[I]);

}

Else printf ("Not a valid binary tree!" );

printf(" \ n ");

}

Running result