Binary trees in Pascal
last modified November 19, 2026 Free Pascal 3.2.2
A binary tree is a structure in which every node has at most two children, called the left child and the right child. In a binary search tree the values are ordered: everything in the left subtree is smaller than the node, and everything in the right subtree is larger. That order makes search, insertion, and deletion proportional to the height of the tree. This article builds a search tree from one insert procedure and one traversal, adds freeing, moves the helpers into a unit, and then adds the other traversals, search, measuring, and deletion in separate steps.
Inserting values and reading them in order
The node type has a value and two pointers, Left and
Right. A nil child pointer marks the absence of a
subtree, so the whole tree is referenced by its root pointer. Insertion compares
the new value with the current node and moves left or right until it finds an
empty place. An in-order traversal visits the left subtree, then the node, then
the right subtree, which prints a search tree in sorted order.
program bst1;
{$mode objfpc}{$H+}
type
PNode = ^TNode;
TNode = record
Value: Integer;
Left, Right: PNode;
end;
function NewNode(Value: Integer): PNode;
begin
New(Result);
Result^.Value := Value;
Result^.Left := nil;
Result^.Right := nil;
end;
procedure Insert(var Root: PNode; Value: Integer);
begin
if Root = nil then
Root := NewNode(Value)
else if Value < Root^.Value then
Insert(Root^.Left, Value)
else if Value > Root^.Value then
Insert(Root^.Right, Value);
end;
procedure PrintInOrder(Node: PNode);
begin
if Node <> nil then
begin
PrintInOrder(Node^.Left);
Write(Node^.Value, ' ');
PrintInOrder(Node^.Right);
end;
end;
var
Root: PNode;
begin
Root := nil;
Insert(Root, 50);
Insert(Root, 30);
Insert(Root, 70);
Insert(Root, 20);
Insert(Root, 40);
Insert(Root, 60);
Insert(Root, 80);
PrintInOrder(Root);
WriteLn;
end.
The root holds 50; 30 and 70 become its left and right children, and the
remaining values fill the next level. A duplicate value is ignored, because the
two comparisons are strict. PrintInOrder writes a space after
every value and the main block ends the line with WriteLn. The program stops without
releasing the nodes: the process exit reclaims them, but a long-running program
would leak. The next section adds a recursive FreeTree.
$ fpc -gl bst1.pas $ ./bst1 20 30 40 50 60 70 80
Freeing the tree
A tree cannot be freed from the root down, because disposing a node first would
lose the addresses of its children. FreeTree therefore visits the
left subtree, then the right subtree, and only then disposes the node. Passing
the node as a var parameter lets the procedure set the caller's
pointer to nil after the release.
program freetree;
{$mode objfpc}{$H+}
type
PNode = ^TNode;
TNode = record
Value: Integer;
Left, Right: PNode;
end;
function NewNode(Value: Integer): PNode;
begin
New(Result);
Result^.Value := Value;
Result^.Left := nil;
Result^.Right := nil;
end;
procedure Insert(var Root: PNode; Value: Integer);
begin
if Root = nil then
Root := NewNode(Value)
else if Value < Root^.Value then
Insert(Root^.Left, Value)
else if Value > Root^.Value then
Insert(Root^.Right, Value);
end;
procedure PrintInOrder(Node: PNode);
begin
if Node <> nil then
begin
PrintInOrder(Node^.Left);
Write(Node^.Value, ' ');
PrintInOrder(Node^.Right);
end;
end;
procedure FreeTree(var Node: PNode);
begin
if Node <> nil then
begin
FreeTree(Node^.Left);
FreeTree(Node^.Right);
Dispose(Node);
Node := nil;
end;
end;
var
Root: PNode;
begin
Root := nil;
Insert(Root, 50);
Insert(Root, 30);
Insert(Root, 70);
Insert(Root, 20);
Insert(Root, 40);
Insert(Root, 60);
Insert(Root, 80);
PrintInOrder(Root);
WriteLn;
FreeTree(Root);
WriteLn('freed: ', Root = nil);
end.
The order used by FreeTree is called post-order: both children come
before their parent. The release runs once per node and uses stack space equal
to the height of the tree. After the call, Root is nil,
so an accidental second traversal would do nothing instead of following a
dangling pointer.
$ fpc -gl freetree.pas $ ./freetree 20 30 40 50 60 70 80 freed: TRUE
A unit for the tree
Every later example needs the node type, Insert,
PrintInOrder, and FreeTree. Rather than repeating them
in each program, they move into a unit called
bst. The types and procedure headers form the
interface; the bodies, unchanged from the previous program, form
the implementation.
unit bst;
{$mode objfpc}{$H+}
interface
type
PNode = ^TNode;
TNode = record
Value: Integer;
Left, Right: PNode;
end;
function NewNode(Value: Integer): PNode;
procedure Insert(var Root: PNode; Value: Integer);
procedure PrintInOrder(Node: PNode);
procedure FreeTree(var Node: PNode);
implementation
function NewNode(Value: Integer): PNode;
begin
New(Result);
Result^.Value := Value;
Result^.Left := nil;
Result^.Right := nil;
end;
procedure Insert(var Root: PNode; Value: Integer);
begin
if Root = nil then
Root := NewNode(Value)
else if Value < Root^.Value then
Insert(Root^.Left, Value)
else if Value > Root^.Value then
Insert(Root^.Right, Value);
end;
procedure PrintInOrder(Node: PNode);
begin
if Node <> nil then
begin
PrintInOrder(Node^.Left);
Write(Node^.Value, ' ');
PrintInOrder(Node^.Right);
end;
end;
procedure FreeTree(var Node: PNode);
begin
if Node <> nil then
begin
FreeTree(Node^.Left);
FreeTree(Node^.Right);
Dispose(Node);
Node := nil;
end;
end;
end.
The unit adds no new behaviour. From now on each program starts with
uses bst; and shows only the procedures that are new in its
section. Compiling such a program compiles bst.pas as well, because
the compiler finds the unit source in the same directory.
Pre-order and post-order
The three traversal orders differ in when the node itself is visited. In-order visits the left subtree, then the node, then the right subtree. Pre-order visits the node before its subtrees, which is useful for copying a tree or writing it to a file. Post-order visits both subtrees before the node, which is the order needed to free the nodes safely.
program traversals;
{$mode objfpc}{$H+}
uses bst;
procedure PrintPreOrder(Node: PNode);
begin
if Node <> nil then
begin
Write(Node^.Value, ' ');
PrintPreOrder(Node^.Left);
PrintPreOrder(Node^.Right);
end;
end;
procedure PrintPostOrder(Node: PNode);
begin
if Node <> nil then
begin
PrintPostOrder(Node^.Left);
PrintPostOrder(Node^.Right);
Write(Node^.Value, ' ');
end;
end;
var
Root: PNode;
begin
Root := nil;
Insert(Root, 50);
Insert(Root, 30);
Insert(Root, 70);
Insert(Root, 20);
Insert(Root, 40);
Insert(Root, 60);
Insert(Root, 80);
Write('in-order: ');
PrintInOrder(Root);
WriteLn;
Write('pre-order: ');
PrintPreOrder(Root);
WriteLn;
Write('post-order: ');
PrintPostOrder(Root);
WriteLn;
FreeTree(Root);
end.
All three functions visit every node exactly once, so each runs in time
proportional to the number of nodes. The recursion stack is as deep as the tree
is high, which matters for a very unbalanced tree. The in-order traversal and
FreeTree come from the bst unit, so the program
contains only the two new procedures and the main block.
$ fpc -gl traversals.pas $ ./traversals in-order: 20 30 40 50 60 70 80 pre-order: 50 30 20 40 70 60 80 post-order: 20 40 30 60 80 70 50
Searching
Search follows the same comparisons as insertion. It can be written as a loop,
since there is no need to return to a parent: start at the root, move left for a
smaller value and right for a larger one, and stop when the value is found or
the pointer becomes nil. The loop uses constant extra space and
takes one step per level.
program search;
{$mode objfpc}{$H+}
uses bst;
function Contains(Node: PNode; Value: Integer): Boolean;
begin
while Node <> nil do
begin
if Value = Node^.Value then
Exit(True)
else if Value < Node^.Value then
Node := Node^.Left
else
Node := Node^.Right;
end;
Result := False;
end;
var
Root: PNode;
begin
Root := nil;
Insert(Root, 50);
Insert(Root, 30);
Insert(Root, 70);
Insert(Root, 20);
Insert(Root, 40);
Insert(Root, 60);
Insert(Root, 80);
WriteLn('contains 40: ', Contains(Root, 40));
WriteLn('contains 45: ', Contains(Root, 45));
FreeTree(Root);
end.
The value 40 is found on the second level, while 45 is absent and the search
ends at a nil child. A search tree with n nodes takes at
most h comparisons, where h is the height. The function
returns a Boolean rather than a pointer, which is enough when the caller only
needs to know whether the value exists.
$ fpc -gl search.pas $ ./search contains 40: TRUE contains 45: FALSE
Height and node count
The height of a tree is the number of nodes on the longest path from the root to a leaf, and the node count is the size of the whole structure. Both are recursive: the empty tree has height 0 and no nodes, and every other tree is one node plus its two subtrees. The minimum and maximum follow the left and right chains until they end.
program stats;
{$mode objfpc}{$H+}
uses bst;
function Height(Node: PNode): Integer;
var
LeftHeight, RightHeight: Integer;
begin
if Node = nil then
Exit(0);
LeftHeight := Height(Node^.Left);
RightHeight := Height(Node^.Right);
if LeftHeight > RightHeight then
Result := LeftHeight + 1
else
Result := RightHeight + 1;
end;
function CountNodes(Node: PNode): Integer;
begin
if Node = nil then
Result := 0
else
Result := 1 + CountNodes(Node^.Left) + CountNodes(Node^.Right);
end;
function MinValue(Node: PNode): Integer;
begin
while Node^.Left <> nil do
Node := Node^.Left;
Result := Node^.Value;
end;
function MaxValue(Node: PNode): Integer;
begin
while Node^.Right <> nil do
Node := Node^.Right;
Result := Node^.Value;
end;
var
Root: PNode;
begin
Root := nil;
Insert(Root, 50);
Insert(Root, 30);
Insert(Root, 70);
Insert(Root, 20);
Insert(Root, 40);
Insert(Root, 60);
Insert(Root, 80);
WriteLn('nodes = ', CountNodes(Root));
WriteLn('height = ', Height(Root));
WriteLn('min = ', MinValue(Root));
WriteLn('max = ', MaxValue(Root));
FreeTree(Root);
end.
The seven-node tree has three levels, so its height is 3. The minimum is found
by following Left until it ends, and the maximum by following
Right. CountNodes and Height both use the
empty tree as the base case, and both run in time proportional to the number of
nodes because each node is visited once.
$ fpc -gl stats.pas $ ./stats nodes = 7 height = 3 min = 20 max = 80
Deleting a leaf or a node with one child
Deletion has three cases. A leaf is removed by replacing its parent's pointer
with nil. A node with one child is replaced by that child. Both
cases are handled by the same code: if the left pointer is nil,
the right child takes the node's place; otherwise, if the right pointer is
nil, the left child takes it.
program delete1;
{$mode objfpc}{$H+}
uses bst;
procedure Delete(var Root: PNode; Value: Integer);
var
Temp: PNode;
begin
if Root = nil then
Exit;
if Value < Root^.Value then
Delete(Root^.Left, Value)
else if Value > Root^.Value then
Delete(Root^.Right, Value)
else if (Root^.Left = nil) or (Root^.Right = nil) then
begin
Temp := Root;
if Root^.Left = nil then
Root := Root^.Right
else
Root := Root^.Left;
Dispose(Temp);
end;
end;
var
Root: PNode;
begin
Root := nil;
Insert(Root, 50);
Insert(Root, 30);
Insert(Root, 70);
Insert(Root, 20);
Insert(Root, 40);
Insert(Root, 35);
Insert(Root, 45);
Write('before: ');
PrintInOrder(Root);
WriteLn;
Delete(Root, 20);
Write('delete leaf: ');
PrintInOrder(Root);
WriteLn;
Delete(Root, 30);
Write('one child: ');
PrintInOrder(Root);
WriteLn;
Delete(Root, 50);
Write('two children: ');
PrintInOrder(Root);
WriteLn;
FreeTree(Root);
end.
Deleting 20 removes a leaf. Deleting 30 then replaces it with its only child, 40, because the left side of 30 became empty when 20 disappeared. Deleting 50 does nothing here: the node has two children, and the procedure deliberately leaves that case for the next section. The tree stays sorted in every case because the replacement child is already on the correct side of the parent.
$ fpc -gl delete1.pas $ ./delete1 before: 20 30 35 40 45 50 70 delete leaf: 30 35 40 45 50 70 one child: 35 40 45 50 70 two children: 35 40 45 50 70
Deleting a node with two children
A node with two children cannot be removed directly without breaking the order. The usual solution is to copy the smallest value from the right subtree into the node and then delete that value from the right subtree. The smallest value has no left child, so its deletion falls into one of the two cases from the previous section.
program delete2;
{$mode objfpc}{$H+}
uses bst;
function MinNode(Node: PNode): PNode;
begin
while Node^.Left <> nil do
Node := Node^.Left;
Result := Node;
end;
procedure Delete(var Root: PNode; Value: Integer);
var
Temp: PNode;
begin
if Root = nil then
Exit;
if Value < Root^.Value then
Delete(Root^.Left, Value)
else if Value > Root^.Value then
Delete(Root^.Right, Value)
else if (Root^.Left = nil) or (Root^.Right = nil) then
begin
Temp := Root;
if Root^.Left = nil then
Root := Root^.Right
else
Root := Root^.Left;
Dispose(Temp);
end
else
begin
Temp := MinNode(Root^.Right);
Root^.Value := Temp^.Value;
Delete(Root^.Right, Temp^.Value);
end;
end;
var
Root: PNode;
begin
Root := nil;
Insert(Root, 50);
Insert(Root, 30);
Insert(Root, 70);
Insert(Root, 20);
Insert(Root, 40);
Insert(Root, 60);
Insert(Root, 80);
Write('before: ');
PrintInOrder(Root);
WriteLn;
Delete(Root, 50);
Write('delete 50: ');
PrintInOrder(Root);
WriteLn;
WriteLn('new root: ', Root^.Value);
FreeTree(Root);
end.
Deleting the root 50, which has two children, copies 60 from the right subtree
into the root and then removes the old 60, so the in-order sequence stays sorted
and 60 becomes the new root. The recursive call searches for the copied value
in the right subtree, where it is now the minimum and has no left child. A value that is not present leaves the
tree unchanged, because the search ends at a nil pointer.
$ fpc -gl delete2.pas $ ./delete2 before: 20 30 40 50 60 70 80 delete 50: 20 30 40 60 70 80 new root: 60
Unbalanced trees
The height determines the cost of every operation. A tree with n nodes can be as short as about log2(n) levels or as tall as n levels. Inserting already sorted values into a plain search tree produces the tall shape: every new value goes to the right, and the structure becomes a linked list with search time linear in the number of nodes.
program skewed;
{$mode objfpc}{$H+}
uses bst;
function Height(Node: PNode): Integer;
var
LeftHeight, RightHeight: Integer;
begin
if Node = nil then
Exit(0);
LeftHeight := Height(Node^.Left);
RightHeight := Height(Node^.Right);
if LeftHeight > RightHeight then
Result := LeftHeight + 1
else
Result := RightHeight + 1;
end;
var
Root: PNode;
I: Integer;
begin
Root := nil;
for I := 1 to 7 do
Insert(Root, I);
WriteLn('ascending insert, height = ', Height(Root));
FreeTree(Root);
Insert(Root, 4);
Insert(Root, 2);
Insert(Root, 6);
Insert(Root, 1);
Insert(Root, 3);
Insert(Root, 5);
Insert(Root, 7);
WriteLn('balanced insert, height = ', Height(Root));
FreeTree(Root);
end.
Seven ascending values produce a height of 7; the same seven values inserted in an order that fills each level produce a height of 3. A balanced tree such as an AVL tree or a red-black tree rebalances itself after insertion and deletion to keep the height logarithmic. The plain search tree in this article does not rebalance, which is acceptable when the input order is random but risky when it is sorted.
$ fpc -gl skewed.pas $ ./skewed ascending insert, height = 7 balanced insert, height = 3
Next steps
The recursion article explains the call pattern behind these traversals, and the stacks and queues article shows the queue used by a level-order traversal. The linked lists article covers the single-pointer node that a tree extends, and the hash tables article compares tree lookup with hashed lookup.
Source
Binary search tree on Wikipedia
In this article we inserted values into a binary search tree, read them in-order, freed the tree, moved the helpers into a unit, added pre-order and post-order traversals, searched for values, measured the height and size, deleted leaves and internal nodes, and compared balanced and skewed shapes. The series continues with Pascal recursion.
Author
List all Pascal tutorials.