module BinaryTreeMain;
public BinaryTreeOutput;
    procedure Infix(NodeIndex : Subscr);
    procedure Prefix(NodeIndex : Subscr);
    procedure Postfix(NodeIndex : Subscr);
public BinaryTreeMain;
    const MaxNumNodes = 20;

    type Subscr = 0..MaxNumNodes;
         Node = record
                   Symbol : char;
                   Left : Subscr;
                   Right : Subscr
                   end;
        Tree = array[Subscr] of Node;

    var NodeCharacter : char;
        NodeIndex : integer;
        ExpressionTree : Tree;

(*  This program builds a binary tree of characters from
user input data and prints out the nodes of a tree in
infix, prefix, and postfix notation.  An input line con-
sists of the character, its position in the tree, and the
position of its two children; each item is separated from
the next by a blank.  *)

program BinaryTreeMain(Input,Output);

const  One = 1;

var    DataFile : text;

(* ---------------------------------------------------*)
procedure BuildTree;    (* build tree from user input *)
var FindRoot : boolean; 

    procedure AddNode;  (* add a node to the tree *)
    begin 
        write(NodeCharacter : 3, NodeIndex: 3);
        with ExpressionTree[NodeIndex] do begin
            Symbol:=NodeCharacter;  
            read(DataFile,Left); write(Left : 3); 
            read(DataFile,Right); write(Right : 3);
            readln(DataFile);
            writeln
            end   
    end; (* AddNode *)

begin 
    FindRoot := false;
    writeln('INPUT IS:'); writeln;
    AddNode;
    repeat
        read(DataFile,NodeCharacter,NodeIndex); 
        if NodeIndex = 1 then FindRoot := true
        else AddNode
    until (FindRoot) or (eof(DataFile));
    writeln               
end;(* BuildTree *)

(* -------------------------------------------------- *)
(* The main program reads in user data and displays the
   tree in Infix, Prefix, and Postfix notation. *)

begin (* BinaryTreeMain *)
    reset(DataFile,':F1:DATA2'); 
    writeln; writeln; writeln;
    read(DataFile,NodeCharacter,NodeIndex);
    while not eof(DataFile) do begin
        BuildTree; 
        writeln; writeln('INFIX:');
        Infix(One);
        writeln; writeln('PREFIX:');
        Prefix(One);
        writeln; writeln('POSTFIX:');
        Postfix(One);
        writeln; writeln
        end;
    writeln; writeln
end. (* BinaryTreeMain *)
