Wikia

Delphi Programming

Basic Binary Tree

2,918pages on
this wiki
Talk0

This is the code for a basic binary tree (or binary search tree) which will maintain a list of integers as the payload. Note that it will not self-balance or otherwise adjust itself to account for the data being inserted.

To use the following class, you'll have to create an instance. For instance (assuming BT is a class variable to TBTreeNode) :

procedure TForm1.Button1Click(Sender: TObject);
var i:integer;
begin
randomize;
for i:=1 to 20 do
   if bt=nil then bt:=TBtreeNode.Create(random(100))
   else           bt.Insert(random(100));
end;

To the display the data, you would then use (assuming the form had a standard listbox component on it):

procedure TForm1.ShowList;
var i:integer;
    TSL:TStringList;
begin
listbox1.clear;
TSL:=TStringList.Create;
bt.OutputInDescendingOrder(TSL);
listbox1.Items.Assign(TSL);
TSL.Free;
end;

where the class is:

type
   TBTreeNode=class
      fRightChild : tbtreenode;
      fLeftChild  : tbtreenode;
      fData       : integer;
      constructor Create(Data:integer);
      destructor Destroy;
      procedure Insert(num:integer);
      procedure OutputInAscendingOrder(TSL:TStringList);
      procedure OutputInDescendingOrder(TSL:TStringList);
    end;

constructor TBTreeNode.Create(Data:integer);
begin
   fData:=data;
   fRightChild:=nil;
   fLeftChild:=nil;
end;

destructor TBTreeNode.Destroy;
begin
   if fRightChild<>nil then fRightChild.Free;
   if fLeftChild<>nil  then fLeftChild.Free;
end;


procedure TBTreeNode.Insert(num:integer);
begin
   if (num<fData) then
      if fLeftChild=nil then fLeftChild:=TBTreeNode.Create(num)
      else                   fLeftChild.Insert(num)
   else
      if fRightChild=nil then fRightChild:=TBTreeNode.Create(num)
      else                    fRightChild.Insert(num)
end;

procedure TBTreeNode.OutputInAscendingOrder(TSL:TStringList);
begin
if TSL=nil then exit;

   if fLeftChild<>nil then fLeftChild.OutputInAscendingOrder(TSL);
   TSL.Add(IntToStr(fData));
   if fRightChild<>nil then fRightChild.OutputInAscendingOrder(TSL);
end;

procedure TBTreeNode.OutputInDescendingOrder(TSL:TStringList);
begin
if TSL=nil then exit;

   if fRightChild<>nil then fRightChild.OutputInDescendingOrder(TSL);
   TSL.Add(IntToStr(fData));
   if fLeftChild<>nil then fLeftChild.OutputInDescendingOrder(TSL);
end;


Code Snippets
DatabasesFiles and I/OForms/WindowsGraphicsNetworkingMath and AlgorithmsMiscellaneousMultimediaSystemVCL

Around Wikia's network

Random Wiki