Page 264, Exercise 5
The following algorithm shows how to construct the tree given the PreOrder and InOrder traversals. The algorithm assumes
that Pre or In represents the characters from each sequence that are currently being compared.
Algorithm CreateTree;
begin
GetNext(Pre);
GetNext(In);
Root's value <= Pre; {first character from prefix is the root}
Parent <= Pre;
GetNext(Pre); {dispose of current character, get the next}
While (Pre contains character) and (In contains characters) do begin
{as long as there are characters in Pre and In, continue}
{constructing the tree}
While (In != Parent's value)do begin
{the nodes will be left children until the Parent's value}
{matches In's value}
Parent.Left's value <= Pre;
GetNext(Pre);
If (Pre== In) then
{Parent found, dispose of it}
GetNext(In)
Else
Parent <= Parent.Left
end; {find the left children}
GetNext(In); {dispose of parent}
While (Pre == In) do begin
{find the right children}
Parent .Right's value <= Pre;
GetNext(Pre);
GetNext(In);
Parent <=Parent.Right
end;
{continue with left children again}
Parent <= node with In's value;
GetNext(In);
Parent.Right's value <= Pre;
GetNext(Pre)
end; {there are values left to process}
end; {CreateTree}