# Include <stdio. h>
# Include <stdlib. h>
# Include <math. h>
Typedef struct Node
{
Char value;
Struct node * leftchild;
Struct node * rightchild;
Int maxleft; // the maximum distance between the current node and all nodes in the left subtree
Int maxright; // the maximum distance between the current node and all nodes in the right subtree
} Treenode;
Int maxlength = 0;
// Construct a binary tree based on the central and forward Sequences
Treenode * createfrommidpre (char mid [], int midleft, int midright, char pre [], int preleft, int preright)
{
Treenode * node = (treenode *) malloc (sizeof (treenode ));
Int midleft1, midright1, preleft1, preright1, rootpos = 0;
If (midright-midleft! = Preright-preleft)
{
Printf ("error: the number of nodes in the input middle sequence is different from that in the front sequence! \ N ");
Return node;
}
Node-> value = pre [preleft];
Node-> leftchild = NULL;
Node-> rightchild = NULL;
For (; Mid [rootpos]! = Pre [preleft]; rootpos ++ );
If (rootpos! = Midleft)
{
Midright1 = rootPos-1;
Preright1 = rootpos-midleft + preleft;
Node-> leftchild = createfrommidpre (MID, midleft, midright1, pre, preleft + 1, preright1 );
}
If (rootpos! = Midright)
{
Midleft1 = rootpos + 1;
Preleft1 = rootpos-midleft + preleft + 1;
Node-> rightchild = createfrommidpre (MID, midleft1, midright, pre, preleft1, preright );
}
Return node;
}
Void findmax (treenode * ptree)
{
If (ptree-> leftchild = NULL)
Ptree-> maxleft = 0;
Else
{
Findmax (ptree-> leftchild );
// The maximum distance between a node and all nodes in the left subtree is the plus one with the largest distance from the left subtree to all nodes in the two subtree.
Ptree-> maxleft = (ptree-> leftchild-> maxleft> ptree-> leftchild-> maxright? Ptree-> leftchild-> maxleft: ptree-> leftchild-> maxright) + 1;
}
If (ptree-> rightchild = NULL)
Ptree-> maxright = 0;
Else
{
Findmax (ptree-> rightchild );
// The maximum distance between a node and all nodes in the right subtree is the plus one with a large distance from the right subtree to all nodes in the two subtree.
Ptree-> maxright = (ptree-> rightchild-> maxleft> ptree-> rightchild-> maxright? Ptree-> rightchild-> maxleft: ptree-> rightchild-> maxright) + 1;
}
If (maxlength <ptree-> maxleft + ptree-> maxright)
Maxlength = ptree-> maxleft + ptree-> maxright;
}
Int main ()
{
Treenode * root1;
Char preseq [20], midseq [20];
Int I = 0, numnode;
Printf ("Enter the total number of nodes: \ n ");
Scanf ("% d", & numnode );
Fflush (stdin );
Printf ("Please input the first sequence: \ n ");
For (I = 0; I <numnode; I ++)
Scanf ("% C", preseq + I );
Fflush (stdin );
Printf ("Please input the central sequence: \ n ");
For (I = 0; I <numnode; I ++)
Scanf ("% C", midseq + I );
Fflush (stdin );
Root1 = createfrommidpre (midseq, 0, I-1, preseq, 0, I-1 );
Findmax (root1 );
Printf ("the two farthest nodes are: % d \ n", maxlength );
Return 1;
}