Chapter 4 Binary Trees

A binary tree is an important type of structure which occurs very often. It is characterized by the fact that any node can have at most two branches, i.e.,there is no node with degree greater than two. For binary trees we distinguish between the subtree on the left and on the right, whereas for trees the order of the subtreewas irrelevant. Also a binary tree may have zero nodes. Thus a binary tree is really a different object than a tree.

Definition: 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.

We can define the data structure binary tree as follows:

structure BTREE

declare CREATE( ) --> btree

ISMTBT(btree,item,btree) --> boolean

MAKEBT(btree,item,btree) --> btree

LCHILD(btree) --> btree

DATA(btree) --> item

RCHILD(btree) --> btree

for all p,r in btree, d in item let

ISMTBT(CREATE)::=true

ISMTBT(MAKEBT(p,d,r))::=false

LCHILD(MAKEBT(p,d,r))::=p; LCHILD(CREATE)::=error

DATA(MAKEBT(p,d,r))::d; DATA(CREATE)::=error

RCHILD(MAKEBT(p,d,r))::=r; RCHILD(CREATE)::=error

end

end BTREE

This set of axioms defines only a minimal set of operations on binary trees. Other operations can usually be built in terms of these. The distinctions between a binary tree and a tree should be analyzed. First of all there is no tree having zero nodes, but there is an empty binary tree. The two binary trees below are different. The first one has an empty right subtree while the second has an empty left subtree. If these are regarded as trees, then they are the same despite the fact that they are drawn slightly differently.

Binary Tree Representations

A full binary tree of depth k is a binary tree of depth k having pow(2,k)-1 nodes. This is the maximum number of the nodes such a binary tree can have. A very elegant sequential representation for such binary trees results from sequentially numbering the nodes, starting with nodes on level 1, then those on level 2 and so on. Nodes on any level are numbered from left to right. This numbering scheme gives us the definition of a complete binary tree. A binary tree with n nodes and a depth k is complete iff its nodes correspond to the nodes which are numbered one to n in the full binary tree of depth k. The nodes may now be stored in a one dimensional array tree, with the node numbered i being stored in tree[i].