Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4034
  • Last Modified:

Binary Trees in Pascal

I want to build a binary tree in pascal from data in a file and then traverse it In-Order and display on screen. So far i have the following but am a bit confused about what to pass into the Traversal procedure as a nodepointer. Any ideas?

Program BinarySearchTrees;


type nodepointer = ^node;

     node = record
     data : string[30];
     left : nodepointer;
     right : nodepointer;
end;


const Datafile = 'C:\MYDOCU~1\UNI\DATAST~1\ASSIGN~1\WORDS425.TXT';

{------------------------------------------------------------------}

Procedure InOrderTraversal (root : nodepointer) ;

begin
   If root^.left <> nil then begin
      InOrderTraversal (root^.left);
      writeln (root^.data);
      end;
   If root^.right <> nil then
      InOrderTraversal (root^.right);

end;

{------------------------------------------------------------------}


Procedure Insert_Into_Tree (n : nodepointer; var root : nodepointer);

begin
     if root = nil then
        root := n
     else begin
        if n^.data > root^.data then
           Insert_Into_Tree(n, root^.right)
        else
           Insert_Into_Tree(n, root^.left)
     end;


end;

{------------------------------------------------------------------}

Procedure Build_Tree;

var s : string;
    newnode: nodepointer;
    root : nodepointer;
begin
     root := nil ;
     assign (input, DataFile);
     reset (input);
     while not eof(input) do begin
           new(newnode);
           readln (input, s);
           newnode^.data := s;
           Insert_Into_Tree (newnode, root);

     end;
     close (input);
     
end;

{---------------------------------------------------------}


begin

Build_Tree;

end.
0
Creamer72
Asked:
Creamer72
  • 2
1 Solution
 
mlmccCommented:
Buildtree needs to have the root pointer passed in otherwise when it ends the tree will also go away.

Procedure Build_Tree (var Root : nodepointer);

var TreeRoot : nodepointer;

begin

Build_Tree (TreeRoot);

end.

Now you can pass TreeRoot to the traversal procedure.

mlmcc
0
 
CleanupPingCommented:
Creamer72:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
mlmccCommented:
I believe I answered it.

mlmcc
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now