iFocus.Life News News - Breaking News & Top Stories - Latest World, US & Local News,Get the latest news, exclusives, sport, celebrities, showbiz, politics, business and lifestyle from The iFocus.Life,

How to Implement a Binary Tree Using Pascal

104 9

Instructions

1

Open a new Pascal file in your text editor or IDE.
2

Add following line to the file:
program bintree;
3

Type the next section of code into your editor to define the basic types for the binary tree:
Type

BinTree = ^Node;
Node = Record
I: integer;
L, R: BinTree;
end;
4

Copy the following into the editor to construct an empty tree:
function MakeTree: BinTree;
begin

MakeTree := nil
end;
5

Place the following source code into your file to test the tree for emptiness:
function IsEmptyTree (B: BinTree): Boolean;
begin

IsEmptyTree := (B = nil);
end;
6

Include the following lines in your script to construct a child node with the given integer value:
function MakeNode (I: integer): BinTree;
var
Res: BinTree;
begin
New (Res);
Res^.I := I;
Res^.L := MakeTree;
Res^.R := MakeTree;
MakeNode := Res;
end;
7

Add these lines to free a tree from the given root node:
procedure DeallocateTree (var B: BinTree);
begin
if not IsEmptyTree (B) then begin

DeallocateTree (B^.L);
DeallocateTree (B^.R);
Dispose (B);

end
end;
8

Place the next section of code into your file to insert the given value into its ordered location in the binary tree.:
procedure InsertInTree (I: integer; var B: BinTree);
begin
if IsEmptyTree (B) then

B := MakeNode (I)
else if I < B^.I then

InsertInTree (I, B^.L)
else

InsertInTree (I, B^.R)
end;
9

Add the following source code to search a tree for a given value:
function FindInTree (S: integer; B: BinTree): Boolean;
begin
if IsEmptyTree (B) then

FindInTree := False
else if S < B^.I then

FindInTree := FindInTree (S, B^.L)
else if B^.I < S then

FindInTree := FindInTree (S, B^.R)
else begin

FindInTree := True
end
end;
10

Paste the next procedure into your Pascal program to see the contents of the tree in sorted order:
procedure PrintTree (B: BinTree);
begin
if not IsEmptyTree (B) then begin

PrintTree (B^.L);
writeln (B^.I);
PrintTree (B^.R)

end
end;
11

Add these last lines to your file to finish the Pascal program:
begin
end.
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time
You might also like on "Technology"

Leave A Reply

Your email address will not be published.