You are on page 1of 11

Chapter 9

Binary Trees

Definition 1: A binary tree is a finite set of nodes which is either empty or consists of a root and two disjoint binary
trees called the left subtree and the right subtree.
Definition 2: a finite set of elements that are either empty or is partitioned into three disjoint subsets. The first
subset contains a single element called the root of the tree. The other two subsets are themselves binary trees,
called the left and the right sub-trees of the original tree. Each element of a binary tree is called a node of the tree.
Definition 3: Collection of nodes and edges such that:
1. All nodes, except the root, have exactly one predecessor. The root has no predecessor.
2. All nodes are reachable by following paths from the root.
Definition of terms
 Node A is called the father of B when B is at the root of A’s left or right sub-tree. The left and right sub-trees
are referred to as the left son and the right son of A.
 Leaf node is a node which has no sons.
 A strictly binary tree is a tree in which every node other than the leaves has two children.
 Level of a node is 0 for the root of the tree and one more than the level of the father for any other node in the
tree. / vertical displacements
 Depth of a binary tree is the maximum level of any leaf in the tree.
 Complete binary tree of depth d is a full binary tree in which all leaves are at the same depth or same level
 Parent – predecessor of a node.
 Child – successor of a node.
 Siblings – nodes having the same parent.
 Degree – number of children of a node.
 Edges – branches.
 Descendant – all nodes you can reach from a given node.
 Ancestor – node on path from root to node.
 Subtree – a node and all its descendants.
 Similar trees – trees that have the same shape.

The figure below depicts two binary trees, in which all nodes have at most two children. For a given node in a
binary tree, the first child is referred to as the left child, while the second child is referred to as the right child.

Illustration of two binary trees


Binary tree (a) has 8 nodes, with node 1 as its root. Node 1's
left child is node 2; node 1's right child is node 3. Notice that
a node doesn't need to have both a left child and right child.
In binary tree (a), node 4, for example, has only a right child.
Furthermore, a node can have no children. In binary tree (b),
nodes 4, 5, 6, and 7 all have no children.
Nodes that have no children are referred to as leaf nodes.
Nodes that have one or two children are referred to as
internal nodes. Using these new definitions, the leaf nodes in
binary tree (a) are nodes 6 and 8; the internal nodes are nodes 1, 2, 3, 4, 5, and 7.

Binary Search Trees (BST)


In a binary search tree all the elements in the left sub-tree of a node n have values less than the contents of n and
all elements in the right sub-tree of n have values bigger than or equal to the contents of n.
Example.
Insert the following elements in an initially empty binary search tree.
70, 50, 30, 80, 60, 90, 55, 76, 20, 85

1
Tree traversals

This refers to passing through the tree and enumerating each of its node once.
We may simply want to print the contents of each node as we enumerate it or process it in some other way. In
either case we speak of using each node as it is enumerated. There are 3 methods of traversing trees these are:-
 Preorder (Depth first order).
 Inorder (symmetric order )
 Post – order

Traversal Algorithms.

Preorder ( RT, L, R).


a) Visit the root.
b) Traverse the left subtree
c) Traverse the right subtree.

Inorder ( L, RE, R)
a) Traverse left subtree.
b) Visit the root node.
c) Traverse the right subtree.

Post order (L, R, RE)


a) Traverse left subtree.
b) Traverse right subtree.
c) Visit the root node.

2
Questions
Obtain the in order, preorder, post order transversals of the following binary trees .

Algorithms
 Building a binary search tree.
type tree = ^node;
node = record
info: integer;
left, right: tree;
end;

procedure addToBst(var t: tree; info: integer);


var head, aux: tree;
begin
if emptyTree(t)
then t := createNode(info)
else begin
aux := t;
head := t;
while not(emptyTree(head)) do begin
aux := head;
if info < getInfo(head)
then head := getLeft(head)
else head := getRight(head);
end;
if info < getInfo(aux)
then setLeft(aux, createNode(info))
else setRight(aux, createNode(info))
end;
end;

3
 Removing duplicates from a list.

We want to develop an algorithm to remove duplicates from a list of numbers.


Idea: we store the numbers in a BST, but as we go down to determine their
position, we check for duplicates.

program removeDuplicates;

const sentinel = -99;

var t, aux, head: tree;number : integer;

begin
write('Enter number: ');
readln(number);
t := createNode(number);
while number <> sentinel do
begin
write('Enter number: ');
readln(number);
if number <> sentinel then begin
aux := t;
head := t;
while (number <> getInfo(aux)) and not(emptyTree(head)) do
begin
aux := head;
if number < getInfo(head)
then head := getLeft(head)
else head := getRight(head);
end;
if number = getInfo(aux)
then writeln(number, ' is a duplicate')
else if number < getInfo(aux)
then setLeft(aux, createNode(number))
else setRight(aux, createNode(number))
end;
end;
end.

 The ADT Tree (Implementation using lists)

type tree = ^node;


node = record
info: integer;
left, right: tree;
end;

function createNode(el: integer): tree;


function createNullTree: tree;
function getInfo(t: tree): integer;
function getLeft(t: tree): tree;
function getRight(t: tree): tree;
procedure setLeft(var t: tree; lst: tree);
procedure setRight(var t:tree; rst: tree);
function emptyTree(t: tree): boolean;

4
function createNode(el: integer): tree;
var temp: tree;
begin
new(temp);
with temp^ do begin
info := el;
left := nil;
right := nil;
end;
createNode := temp;
end;

function createNullTree: tree;


begin
createNullTree := nil;
end;

function getInfo(t: tree): integer;


begin
getInfo := t^.info;
end;

function getLeft(t: tree): tree;


begin
getLeft := t^.left;
end;

function getRight(t: tree): tree;


begin
getRight := t^.right;
end;

procedure setLeft(var t: tree; lst: tree);


begin
t^.left := lst;
end;

procedure setRight(var t:tree; rst: tree);


begin
t^.right := rst;
end;

function emptyTree(t: tree): boolean;


begin
emptyTree := t = nil;
end;

5
 Trees using ARRAY implementation.
const maxNodes = 500;
type index = 1..maxNodes;
node = record
info: integer;
left: 0..maxNodes;
right: 0..maxNodes;
end;
bintree = record
elements = array[index] of node;
root = 0..maxindex;
end;
var bt: binTree;

Example

bt = 1
1 2 3 4 5 6 7 8 9 10
info 25 6 15 50 40 30 14 20 30 75
left 3 0 2 0 6 0 0 0 0 0
right 5 0 8 10 4 0 0 0 0 0

How to find a free node? Use a special value for left or right!
Construct a free-list.

 Implicit ARRAY implementation / Sequential representation

const maxNodes = 500;


type index = 1..maxNodes;
bintree = array[index] of integer;
var bt: bintree;

 Example:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
25 15 40 6 20 30 50 75

How do we know if a node is used? Special value or extra field!

Advantage: we can go to a node’s father.


Disadvantage: use of space in the array.

6
1. HETEROGENEOUS BINARY TREES.
A heterogeneous binary tree is a tree in which the information field of different nodes might have a different type.

 Example: expression trees


:- are trees whose interior nodes represent an operation (e.g., addition, multiply) and leaf node represent
operands, for example below for the expression (a – (c/d)) + (5 * b):-

3 + 4 * (6 - 7) / 5 + 1

evaluate(expTree):
case expTree^.infoKind of
operand: evaluate := expTree^.info
operator: begin
opnd1 := evaluate(getLeft(expTree));
opnd2 := evaluate(getRight(expTree));
oper := getInfo(expTree^.info);
evaluate := calculate(oper, opnd1, opnd2);
end;
end;

7
1. THREADED BINARY TREES
Observation:: lots of pointers in a tree have the nil value
traversing a tree is a recursive process

Idea: use some of those nil pointers as guides for traversing the tree

Right In-threaded binary tree:


A node with an empty right subtree has its right field pointing to the in-order successor of that node.

 Example

b c

d e f

g h i

8
1. GENERAL TREES.
A tree is a finite nonempty set of elements in which one element is called the root and the remaining elements are
partitioned into m>=o disjoint subsets, each of which itself is a tree.
The degree of a node is defined as its number of sons.

Example:

Implementation:

using arrays:
const maxSons = 20;
type tree = ^node;
node = record
info: integer;
sons: array[1..maxSons] of tree;
end;

using pointers:
type tree = ^node;
node = record
info: integer;
sons: tree;
brother: tree;
end;

9
How much do you understand about general tree/search algorithms? There is ALOT of
information which you need to master in order to understand these. Use your text book, find a
book, search on the internet. You are not likely to find someone willing to just give you the work
that he/she did and which you are trying to get out of ...

The binary tree is based upon the concept that the "root" node has a larger value then its left
child, and a smaller value than its right child

therefore, if you move to a left child you are moving to a smaller value, to a right child you are
moving to a larger value.

Search:

Is the root the value I'm looking for? If yes, I'm done
Is the value in root larger than the value I'm looking for?
if yes,
if there is no left child, stop - you did not find the value in the tree
if there is a left child, move to the left child , recursively call this search using the left child as
the "root"
else
if there is no right child, stop - you did not find the value in the tree
if there is a right child, move to the right child, recursively call this search using the right child as
the "root"

Insert:
Is the value in the root equal to the value? If yes, I'm done (if this is a set)
Is the value in the root larger than the value I'm looking for?
if yes,
if there is no left child, insert this value in the tree as the left child
if there is a left child, move to the left child, recursively call this insert
else
if there is no right child, insert the value in the tree as the right child
if there is a right child, move to the right child, recursively call this insert

OTHERWISE, use search, if the value is not in the tree, return the node which was the last node
you looked at, it will become the "root" of this sub-tree, the place where you will be inserting,
then insert at that location as left or right child, as appropriate ...

Delete - search - if found, delete, making appropriate new parent/child connection as your
situation may require

Print minimum - go root, move left, move left, move left until there is no left child - that is your
minimum value

Your inorder searches are a recursive call to move left, visit, move right ... whether your visit is
to print out or do some other function ...

10
11

You might also like