Binary Trees
Binary Trees
Binary Trees
5
Binary Trees
A data structure is said to be linear if its elements form a sequence or a
linear list. Previous linear data structures that we have studied like an
array, stacks, queues and linked lists organize data in linear order. A data
structure is said to be non linear if its elements form a hierarchical
classification where, data items appear at various levels.
Trees and Graphs are widely used non-linear data structures. Tree and
graph structures represents hierarchial relationship between individual
data elements. Graphs are nothing but trees with certain restrictions
removed.
5.1. TREES:
A tree is hierarchical collection of nodes. One of the nodes, known as the root, is at the
top of the hierarchy. Each node can have at most one link coming into it. The node
where the link originates is called the parent node. The root node has no parent. The
links leaving a node (any number of links are allowed) point to child nodes. Trees are
recursive structures. Each child node is itself the root of a subtree. At the bottom of
the tree are leaf nodes, which have no children.
Trees represent a special case of more general structures known as graphs. In a graph,
there is no restrictions on the number of links that can enter or leave a node, and
cycles may be present in the graph. The figure 5.1.1 shows a tree and a non-tree.
a
a
b c b c
d e f d e
In a tree data structure, there is no distinction between the various children of a node
i.e., none is the "first child" or "last child". A tree in which such distinctions are made is
called an ordered tree, and data structures built on them are called ordered tree
data structures. Ordered trees are by far the commonest form of tree data structure.
In general, tree nodes can have any number of children. In a binary tree, each node
can have at most two children. A binary tree is either empty or consists of a node
called the root together with two binary trees called the left subtree and the right
subtree.
A tree with no nodes is called as a null tree. A binary tree is shown in figure 5.2.1.
l
e
ft
ch
i
l
d B Cr
i
g
htc
h
i
l
d
r
i
g
hts
u
b
tr
e
e
l
e
ft
su
b
t
re
e DE FG
HI
F
i
g
ur
e5
.
2
.1
.
Bi
n
ar
yT
r
e
e
Binary trees are easy to implement because they have a small, fixed number of child
links. Because of this characteristic, binary trees are the most common types of trees
and form the basis of many important data structures.
Tree Terminology:
Leaf node
A node with no children is called a leaf (or external node). A node which is not
a leaf is called an internal node.
Path
A sequence of nodes n1, n2, . . ., nk, such that ni is the parent of ni + 1 for i = 1,
2,. . ., k - 1. The length of a path is 1 less than the number of nodes on the
path. Thus there is a path of length zero from a node to itself.
For the tree shown in figure 5.2.1, the path between A and I is A, B, D, I.
Siblings
For the tree shown in figure 5.2.1, F and G are the siblings of the parent node C
and H and I are the siblings of the parent node D.
Subtree
Height
The maximum level in a tree determines its height. The height of a node in a
tree is the length of a longest path from the node to a leaf. The term depth is
also used to denote height of the tree. The height of the tree of Figure 5.2.1 is
3.
Depth
The depth of a node is the number of nodes along the path from the root to that
node. For instance, node ‘C’ in figure 5.2.1 has a depth of 1.
The nodes of a binary tree can be numbered in a natural way, level by level, left
to right. The nodes of a complete binary tree can be numbered so that the root
is assigned the number 1, a left child is assigned twice the number assigned its
parent, and a right child is assigned one more than twice the number assigned
its parent. For example, see Figure 5.2.2.
Level 0
1
Level 1
2 3
Level 2
4 5 6 7
Level 3
8 9
3. Since a binary tree can contain at most one node at level 0 (the root), it can
contain at most 2l node at level l.
If every non-leaf node in a binary tree has nonempty left and right subtrees, the
tree is termed as strictly binary tree. Thus the tree of figure 5.2.3(a) is strictly
binary. A strictly binary tree with n leaves always contains 2n - 1 nodes.
A full binary tree of height h has all its leaves at level h. Alternatively; All non
leaf nodes of a full binary tree have two children, and the leaf nodes have no
children.
A full binary tree with height h has 2h + 1 - 1 nodes. A full binary tree of height h
is a strictly binary tree all of whose leaves are at level h. Figure 5.2.3(d)
illustrates the full binary tree containing 15 nodes and of height 3.
A full binary tree of height h contains 2h leaves and, 2h - 1 non-leaf nodes.
h
Thus by induction, total number of nodes ( tn) 2 l 2 h 1 1 .
l 0
1
1 Strict Binary Tree
(a)
2 3
2 3
6 7 4 5 6 7
1
1
2 3
2 3
4 5 6 7
4 5 6 7
8 9 10 11 12 13 14 15
8 9 10
A binary tree with n nodes is said to be complete if it contains all the first n
nodes of the above numbering scheme. Figure 5.2.4 shows examples of
complete and incomplete binary trees.
A complete binary tree of height h looks like a full binary tree down to level h-1,
and the level h is filled from left to right.
1 1 1
2 3 2 3 2
4 5 6 4 5 7 4
Complete Binary Tree Not C omplete and not Not C omplete and not
but not strict strict strict
(a) (b) (c)
We define two terms: Internal nodes and external nodes. An internal node is a tree
node having at least one–key and possibly some children. It is some times convenient
to have another types of nodes, called an external node, and pretend that all null child
links point to such a node. An external node doesn’t exist, but serves as a conceptual
place holder for nodes to be inserted.
We draw internal nodes using circles, with letters as labels. External nodes are denoted
by squares. The square node version is sometimes called an extended binary tree. A
binary tree with n internal nodes has n+1 external nodes. Figure 5.2.6 shows a sample
tree illustrating both internal and external nodes.
a d Internal Nodes: a, b, c, d
External Nodes: 1, 2, 3, 4, 5
1 b 4 5
2 3
Array-based Implementation:
Binary trees can also be stored in arrays, and if the tree is a complete binary tree, this
method wastes no space. In this compact arrangement, if a node has an index i, its
children are found at indices 2i+1 and 2i+2, while its parent (if any) is found at index
floor((i-1)/2) (assuming the root of the tree stored in the array at an index zero).
This method benefits from more compact storage and better locality of reference,
particularly during a preorder traversal. However, it requires contiguous memory,
0 1 2 3 4 5 6
Array representation is good for complete binary tree, but it is wasteful for many other
binary trees. The representation suffers from insertion and deletion of node from the
middle of the tree, as it requires the moment of potentially many nodes to reflect the
change in level number of this node. To overcome this difficulty we represent the
binary tree in linked representation.
In linked representation each node in a binary has three fields, the left child field
denoted as LeftChild, data field denoted as data and the right child field denoted as
RightChild. If any sub-tree is empty then the corresponding pointer’s LeftChild and
RightChild will store a NULL value. If the tree itself is empty the root pointer will store a
NULL value.
Memory spaces are wasted for storing NULL pointers for the nodes, which
have no subtrees.
The structure definition, node representation empty binary tree is shown in figure 5.2.6
and the linked representation of binary tree using this node structure is given in figure
5.2.7.
B C
A
D E F G
B C
H I
D X E X X F X X G X
X H X X I X
A tree traversal is a method of visiting every node in the tree. By visit, we mean that
some type of operation is performed. For example, you may wish to print the contents
of the nodes.
1. Preorder
2. Inorder
3. Postorder
4. Level order
In the first three traversal methods, the left subtree of a node is traversed before the
right subtree. The difference among them comes from the difference in the time at
which a root node is visited.
Inorder Traversal:
In the case of inorder traversal, the root of each subtree is visited after its left subtree
has been traversed but before the traversal of its right subtree begins. The steps for
traversing a binary tree in inorder traversal are:
Preorder Traversal:
In a preorder traversal, each root node is visited before its left and right subtrees are
traversed. Preorder search is also called backtracking. The steps for traversing a binary
tree in preorder traversal are:
Postorder Traversal:
In a postorder traversal, each root is visited after its left and right subtrees have been
traversed. The steps for traversing a binary tree in postorder traversal are:
In a level order traversal, the nodes are visited level by level starting from the root,
and going from left to right. The level order traversal requires a queue data structure.
So, it is not possible to develop a recursive procedure to traverse the binary tree in
level order. This is nothing but a breadth first search technique.
The algorithm for level order traversal is as follows:
Example 1:
Traverse the following binary tree in pre, post, inorder and level order.
A • P r eo r d e r t r a v e rs a l y ie lds:
A , B , D, C , E, G , F , H , I
B C
• Po sto r d e r t r a v e rs a l y ie lds:
D, B , G , E, H , I, F , C , A
D E F
• Ino r d e r t r a v e rs a l y ie lds:
G H I D, B , A , E, G , C , H , F , I
• L e v e l o r d e r t r a v e rs a l y ie lds:
A , B , C , D, E, F , G , H , I
Bi n a ry T r e e Pr e, P o st , I n or d er a n d l ev e l or d er T r av e rs i n g
Example 2:
Traverse the following binary tree in pre, post, inorder and level order.
• P r eo r d e r t r a v e rs a l y ie lds:
P
P , F , B , H , G , S , R, Y , T , W , Z
F S
• Po sto r d e r t r a v e rs a l y ie lds:
B H R Y
B, G , H, F , R, W , T, Z, Y, S, P
• Ino r d e r t r a v e rs a l y ie lds:
G T Z B, F , G , H, P, R, S, T, W , Y, Z
W • L e v e l o r d e r t r a v e rs a l y ie lds:
P, F , S, B, H, R, Y, G , T, Z, W
Bi n a ry T r e e Pr e, P o st , I n or d er a n d l ev e l or d er T r av e rs i n g
Example 3:
Traverse the following binary tree in pre, post, inorder and level order.
• Ino r d e r t r a v a rs a l y ie lds:
5 11 4 2 , 7 , 5 , 6 , 11 , 2 , 5 , 4 , 9
• L e v e l o r d e r t r a v e rs a l y ie lds:
2, 7 , 5 , 2 , 6 , 9 , 5 , 11 , 4
Bi n a ry T r e e Pr e, P o st , I n or d er a n d l ev e l or d er T r av e rs i n g
Example 4:
Traverse the following binary tree in pre, post, inorder and level order.
• P r eo r d e r t r a v e rs a l y ie lds:
A A , B , D, G , K , H , L , M , C , E
B C
• Po sto r d e r t r a v a rs a l y ie lds:
K , G , L , M , H , D, B , E, C , A
D E
• Ino r d e r t r a v a rs a l y ie lds:
G H K , G , D, L , H , M , B , A , E, C
K L M • L e v e l o r d e r t r a v e rs a l y ie lds:
A , B , C , D, E, G , H , K, L , M
Bi n a ry T r e e Pr e, P o st , I n or d er a n d l ev e l or d er T r av e rs i n g
Sometimes it is required to construct a binary tree if its traversals are known. From a
single traversal it is not possible to construct unique binary tree. However any of the
two traversals are given then the corresponding tree can be drawn uniquely:
If the preorder traversal is given, then the first node is the root node. If the postorder
traversal is given then the last node is the root node. Once the root node is identified,
all the nodes in the left sub-trees and right sub-trees of the root node can be identified
using inorder.
It can be noted that, for the purpose mentioned, two traversal are essential out of
which one should be inorder traversal and another preorder or postorder; alternatively,
given preorder and postorder traversals, binary tree cannot be obtained uniquely.
Example 1:
Preorder: A B D G C E H I F
Inorder: D G B A H E I C F
Solution:
From Inorder sequence D G B A H E I C F, we get the left and right sub trees:
D G B H E I C F
From the inorder sequence D G B, we can find that D and G are to the left of B.
B H E I C F
D G
From the inorder sequence D G, we can find that there is no left node to D and G is at
the right of D.
B H E I C F
From the preorder sequence C E H I F, the root of the left sub tree is: C
From the inorder sequence H E I C F, we can find that H E I are at the left of C and F is
at the right of C.
B C
D H E I F
From the inorder sequence H E I, we can find that H is at the left of E and I is at the
right of E.
B C
D E F
G H I
Example 2:
Inorder: D G B A H E I C F
Postorder: G D B H I E F C A
Solution:
From Inorder sequence D G B A H E I C F, we get the left and right sub trees:
D G B H E I C F
From the inorder sequence D G B, we can find that D G are to the left of B and there is
no right subtree for B.
B H E I C F
D G
From the inorder sequence D G, we can find that is no left subtree for D and G is to the
right of D.
B H E I C F
From the postorder sequence H I E F C, the root of the left sub tree is: C
From the inorder sequence H E I C F, we can find that H E I are to the left of C and F is
the right subtree for C.
The Binary tree upto this point looks like:
B C
D H E I F
From the inorder sequence H E I, we can find that H is left subtree for E and I is to the
right of E.
B C
D E F
G H I
Example 3:
Inorder: n1 n2 n3 n4 n5 n6 n7 n8 n9
Preorder: n6 n2 n1 n4 n3 n5 n9 n7 n8
Solution:
From Inorder sequence n1 n2 n3 n4 n5 n6 n7 n8 n9, we get the left and right sub
trees:
n6
n1 n2 n3 n4 n5 n7 n8 n9
To find the root, left and right sub trees for n1 n2 n3 n4 n5:
From the inorder sequence n1 n2 n3 n4 n5, we can find that n1 is to the left of n2 and
n3 n4 n5 are to the right of n2. The Binary tree upto this point looks like:
n6
n2 n7 n8 n9
n1 n3 n4 n5
To find the root, left and right sub trees for n3 n4 n5:
From the preorder sequence n4 n3 n5, the root of the tree is: n4
From the inorder sequence n3 n4 n5, we can find that n3 is to the left of n4 and n5 is
at the right of n4.
n6
n2 n7 n8 n9
n1 n4
n3 n5
To find the root, left and right sub trees for n7 n8 n9:
From the preorder sequence n9 n7 n8, the root of the left sub tree is: n9
From the inorder sequence n7 n8 n9, we can find that n7 and n8 are at the left of n9
and no right subtree of n9.
n6
n9
n2
n1 n4 n7 n8
n3 n5
To find the root, left and right sub trees for n7 n8:
From the preorder sequence n7 n8, the root of the tree is: n7
n6
n9
n2
n1 n4 n7
n3 n5 n8
Example 4:
Inorder: n1 n2 n3 n4 n5 n6 n7 n8 n9
Postorder: n1 n3 n5 n4 n2 n8 n7 n9 n6
Solution:
From Inorder sequence n1 n2 n3 n4 n5 n6 n7 n8 n9, we get the left and right sub
trees:
n6
n1 n2 n3 n4 n5 n7 n8 n9
To find the root, left and right sub trees for n1 n2 n3 n4 n5:
From the inorder sequence n1 n2 n3 n4 n5, we can find that n1 is to the left of n2 and
n3 n4 n5 are to the right of n2.
n6
n2 n7 n8 n9
n1 n3 n4 n5
From the postorder sequence n3 n5 n4, the root of the tree is: n4
From the inorder sequence n3 n4 n5, we can find that n3 is to the left of n4 and n5 is
to the right of n4. The Binary tree upto this point looks like:
n6
n2 n7 n8 n9
n1 n4
n3 n5
To find the root, left and right sub trees for n7 n8 and n9:
From the postorder sequence n8 n7 n9, the root of the left sub tree is: n9
From the inorder sequence n7 n8 n9, we can find that n7 and n8 are to the left of n9
and no right subtree for n9.
n6
n2 n9
n1 n4 n7 n8
n3 n5
To find the root, left and right sub trees for n7 and n8:
From the postorder sequence n8 n7, the root of the tree is: n7
From the inorder sequence n7 n8, we can find that there is no left subtree for n7 and
n8 is to the right of n7. The Binary tree upto this point looks like:
n6
n2 n9
n1 n4 n7
n3 n5 n8
# include <stdio.h>
# include <stdlib.h>
struct tree
{
struct tree* lchild;
char data[10];
struct tree* rchild;
};
node* getnode()
{
node *temp ;
temp = (node*) malloc(sizeof(node));
printf("\n Enter Data: ");
scanf("%s",temp->data);
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
void create_fbinarytree()
{
int j, i=0;
printf("\n How many nodes you want: ");
scanf("%d",&ctr);
tree[0] = getnode();
j = ctr;
j--;
do
{
if( j > 0 ) /* left child */
{
tree[ i * 2 + 1 ] = getnode();
tree[i]->lchild = tree[i * 2 + 1];
j--;
}
if( j > 0 ) /* right child */
{
tree[i * 2 + 2] = getnode();
j--;
tree[i]->rchild = tree[i * 2 + 2];
}
i++;
} while( j > 0);
}
void levelorder()
{
int j;
for(j = 0; j < ctr; j++)
{
if(tree[j] != NULL)
printf("%3s",tree[j]->data);
}
}
void main()
{
int i;
create_fbinarytree();
printf("\n Inorder Traversal: ");
inorder(tree[0]);
printf("\n Preorder Traversal: ");
preorder(tree[0]);
printf("\n Postorder Traversal: ");
postorder(tree[0]);
printf("\n Level Order Traversal: ");
levelorder();
printf("\n Leaf Nodes: ");
print_leaf(tree[0]);
printf("\n Height of Tree: %d ", height(tree[0]));
}
# include <stdio.h>
# include <stdlib.h>
struct tree
{
struct tree* lchild;
char data[10];
struct tree* rchild;
};
node* getnode()
{
node *temp ;
temp = (node*) malloc(sizeof(node));
printf("\n Enter Data: ");
fflush(stdin);
scanf("%s",temp->data);
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
int menu()
{
int ch;
clrscr();
printf("\n 1. Create Binary Tree ");
printf("\n 2. Inorder Traversal ");
printf("\n 3. Preorder Traversal ");
printf("\n 4. Postorder Traversal ");
printf("\n 5. Level Order Traversal");
printf("\n 6. Leaf Node ");
printf("\n 7. Print Height of Tree ");
printf("\n 8. Print Binary Tree ");
printf("\n 9. Delete a node ");
printf("\n 10. Quit ");
printf("\n Enter Your choice: ");
scanf("%d", &ch);
return ch;
}
void main()
{
int i,ch;
node *root = NULL;
do
{
ch = menu();
switch( ch)
{
case 1 :
if( root == NULL )
{
root = getnode();
create_binarytree(root);
}
else
{
printf("\n Tree is already Created ..");
}
break;
case 2 :
printf("\n Inorder Traversal: ");
inorder(root);
break;
case 3 :
printf("\n Preorder Traversal: ");
preorder(root);
break;
At first glance, it appears that we would always want to use the flat traversal functions
since they use less stack space. But the flat versions are not necessarily better. For
instance, some overhead is associated with the use of an explicit stack, which may
negate the savings we gain from storing only node pointers. Use of the implicit function
call stack may actually be faster due to special machine instructions that can be used.
Inorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the following
steps until the stack is empty:
1. Proceed down the left most path rooted at vertex, pushing each vertex onto the
stack and stop when there is no left son of vertex.
2. Pop and process the nodes on stack if zero is popped then exit. If a vertex with
right son exists, then set right son of vertex as current vertex and return to step
one.
Algorithm inorder()
{
stack[1] = 0
vertex = root
top: while(vertex ≠ 0)
{
push the vertex into the stack
vertex = leftson(vertex)
while(vertex ≠ 0)
{
print the vertex node
if(rightson(vertex) ≠ 0)
{
vertex = rightson(vertex)
goto top
}
pop the element from the stack and made it as vertex
}
}
Preorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the following
steps until the stack is empty:
1. Proceed down the left most path by pushing the right son of vertex onto stack,
if any and process each vertex. The traversing ends after a vertex with no left
child exists.
2. Pop the vertex from stack, if vertex ≠ 0 then return to step one otherwise exit.
Algorithm preorder( )
{
stack[1] = 0
vertex = root.
while(vertex ≠ 0)
{
print vertex node
if(rightson(vertex) ≠ 0)
push the right son of vertex into the stack.
if(leftson(vertex) ≠ 0)
vertex = leftson(vertex)
else
pop the element from the stack and made it as vertex
}
}
Postorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the following
steps until the stack is empty:
1. Proceed down the left most path rooted at vertex. At each vertex of path push
vertex on to stack and if vertex has a right son push –(right son of vertex) onto
stack.
2. Pop and process the positive nodes (left nodes). If zero is popped then exit. If a
negative node is popped, then ignore the sign and return to step one.
top: while(vertex ≠ 0)
{
push vertex onto stack
if(rightson(vertex) ≠ 0)
push – (vertex) onto stack
vertex = leftson(vertex)
}
pop from stack and make it as vertex
while(vertex > 0)
{
print the vertex node
pop from stack and make it as vertex
}
if(vertex < 0)
{
vertex = - (vertex)
goto top
}
}
Example 1:
Traverse the following binary tree in pre, post and inorder using non-recursive
traversing algorithm.
A
• P r eo r d e r t r a v e rs a l y ie lds:
B C A , B , D, G , K , H , L , M , C , E
D E • Po sto r d e r t r a v a rs a l y ie lds:
K , G , L , M , H , D, B , E, C , A
G H
• Ino r d e r t r a v a rs a l y ie lds:
K , G , D, L , H , M , B , A , E, C
K L M
Bi n a ry T r e e Pr e, P o st a n d I n or d er T r av er s i n g
Inorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the following
steps until the stack is empty:
1. Proceed down the left most path rooted at vertex, pushing each vertex onto the
stack and stop when there is no left son of vertex.
2. Pop and process the nodes on stack if zero is popped then exit. If a vertex with
right son exists, then set right son of vertex as current vertex and return to step
one.
K 0ABDG K POP K
E 0C KGDLHMBAE POP E
Postorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the following
steps until the stack is empty:
1. Proceed down the left most path rooted at vertex. At each vertex of path push
vertex on to stack and if vertex has a right son push –(right son of vertex) onto
stack.
2. Pop and process the positive nodes (left nodes). If zero is popped then exit. If a
negative node is popped, then ignore the sign and return to step one.
CURRENT
STACK PROCESSED NODES REMARKS
VERTEX
A 0 PUSH 0
PUSH the left most path of A with a
0 A –C B D –H G K
-ve for right sons
0 A –C B D –H KG POP all +ve nodes K and G
H 0 A –C B D KG Pop H
PUSH the left most path of H with a
0 A –C B D H –M L KG
-ve for right sons
M 0 A –C B D H KGL Pop M
PUSH the left most path of M with a
0 A –C B D H M KGL
-ve for right sons
0 A –C KGLMHDB POP all +ve nodes M, H, D and B
C 0A KGLMHDB Pop C
PUSH the left most path of C with a
0ACE KGLMHDB
-ve for right sons
0 KGLMHDBECA POP all +ve nodes E, C and A
Preorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the following
steps until the stack is empty:
1. Proceed down the left most path by pushing the right son of vertex onto stack,
if any and process each vertex. The traversing ends after a vertex with no left
child exists.
2. Pop the vertex from stack, if vertex ≠ 0 then return to step one otherwise exit.
CURRENT
STACK PROCESSED NODES REMARKS
VERTEX
A 0 PUSH 0
PUSH the right son of each vertex onto stack and
0CH ABDGK
process each vertex in the left most path
H 0C ABDGK POP H
PUSH the right son of each vertex onto stack and
0CM ABDGKHL
process each vertex in the left most path
M 0C ABDGKHL POP M
PUSH the right son of each vertex onto stack and
0C ABDGKHLM process each vertex in the left most path; M has
no left path
C 0 ABDGKHLM Pop C
PUSH the right son of each vertex onto stack and
0 ABDGKHLMCE process each vertex in the left most path; C has
no right son on the left most path
0 ABDGKHLMCE Stop since stack is empty
Example 2:
2 • P r eo r d e r t r a v e rs a l y ie lds:
2, 7 , 2 , 6 , 5 , 11 , 5 , 9 , 4
7 5
• Po sto r d e r t r a v a rs a l y ie lds:
2 6 9 2, 5 , 11 , 6 , 7 , 4 , 9 , 5 , 2
5 11 4 • Ino r d e r t r a v a rs a l y ie lds:
2 , 7 , 5 , 6 , 11 , 2 , 5 , 4 , 9
Bi n a ry T r e e Pr e, P o st a n d I n or d er T r av ers i n g
Inorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the following
steps until the stack is empty:
1. Proceed down the left most path rooted at vertex, pushing each vertex onto the
stack and stop when there is no left son of vertex.
2. Pop and process the nodes on stack if zero is popped then exit. If a vertex with
right son exists, then set right son of vertex as current vertex and return to step
one.
0272
2 027 2
7 02 27
6 0265 27
5 026 275
6 02 2756
11 0 2 11 2756
11 02 2 7 5 6 11
2 0 2 7 5 6 11 2
5 05 2 7 5 6 11 2
5 0 2 7 5 6 11 2 5
9 094 2 7 5 6 11 2 5
4 09 2 7 5 6 11 2 5 4
Postorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the following
steps until the stack is empty:
2. Pop and process the positive nodes (left nodes). If zero is popped then exit. If a
negative node is popped, then ignore the sign and return to step one.
Preorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the following
steps until the stack is empty:
1. Proceed down the left most path by pushing the right son of vertex onto stack,
if any and process each vertex. The traversing ends after a vertex with no left
child exists.
2. Pop the vertex from stack, if vertex ≠ 0 then return to step one otherwise exit.
Expression tree is a binary tree, because all of the operations are binary. It is also
possible for a node to have only one child, as is the case with the unary minus
Inorder Traversal
Preorder Traversal
Postorder Traversal
Figure 5.4.1 shows some more expression trees that represent arithmetic expressions
given in infix form.
+ +
+ / + d
a b c d + c
+ *
- + + *
a x y b c a
An expression tree can be generated for the infix and postfix expressions.
Example 1:
The first two symbols are operands, so we create one-node trees and push pointers to
them onto a stack.
a b
Next, a ‘+’ is read, so two pointers to trees are popped, a new tree is formed, and a
pointer to it is pushed onto the stack.
a b
Next, c, d, and e are read, and for each one–node tree is created and a pointer to the
corresponding tree is pushed onto the stack.
a b c d e
+
+ c +
a bb d e
+
+ *
a b c +
d ee
Finally, the last symbol is read, two trees are merged, and a pointer to the final tree is
left on the stack.
+
*
+ *
a b c +
d e
e
Example 2:
(A + B * C) – ((D * E + F) / G)
Solution:
First convert the infix expression into postfix notation. Postfix notation of the arithmetic
expression is: A B C * + D E * F + G / -
The first three symbols are operands, so we create one-node trees and pointers to
three nodes pushed onto the stack.
Next, a ‘*’ is read, so two pointers to trees are popped, a new tree is formed, and a
pointer to it is pushed onto the stack.
A *
B C
Next, a ‘+’ is read, so two pointers to trees are popped, a new tree is formed, and a
pointer to it is pushed onto the stack.
A
*
B C
Next, D and E are read, and for each one–node tree is created and a pointer to the
corresponding tree is pushed onto the stack.
+ D E
A
*
B C
Continuing, a ‘*’ is read, so we pop two tree pointers and form a new tree with a ‘*’ as
root.
+ *
A * D E
B C
+
-
+ /
A * + G
B C * F
D E
Let us convert the following expressions from one type to another. These can be as
follows:
1. Postfix to infix
2. Postfix to prefix
3. Prefix to infix
4. Prefix to postfix
1. Postfix to Infix:
The following algorithm works for the expressions whose infix form does not require
parenthesis to override conventional precedence of operators.
2. Postfix to Prefix:
The following algorithm works for the expressions to convert postfix to prefix:
3. Prefix to Infix:
The following algorithm works for the expressions whose infix form does not require
parenthesis to override conventional precedence of operators.
4. Prefix to postfix:
The linked representation of any binary tree has more null links than actual pointers. If
there are 2n total links, there are n+1 null links. A clever way to make use of these null
links has been devised by A.J. Perlis and C. Thornton.
Their idea is to replace the null links by pointers called Threads to other nodes in the
tree.
If the RCHILD(p) is normally equal to zero, we will replace it by a pointer to the node
which would be printed after P when traversing the tree in inorder.
A null LCHILD link at node P is replaced by a pointer to the node which immediately
precedes node P in inorder. For example, Let us consider the tree:
B C
D E F G
H I
B C
D E F G
H I
The tree has 9 nodes and 10 null links which have been replaced by Threads. If we
traverse T in inorder the nodes will be visited in the order H D I B E A F C G.
For example, node ‘E’ has a predecessor Thread which points to ‘B’ and a successor
Thread which points to ‘A’. In memory representation Threads and normal pointers are
distinguished between as by adding two extra one bit fields LBIT and RBIT.
1 - 1
-
A
1 A 1
1 B 1 1 C 1
1 D 1 0 E 0 0 F 0 0 G 0
0 H 0 0 I 0
A binary search tree is a binary tree. It may be empty. If it is not empty then it
satisfies the following properties:
1. Every element has a key and no two elements have the same key.
2. The keys in the left subtree are smaller than the key in the root.
3. The keys in the right subtree are larger than the key in the root.
4. The left and right subtrees are also binary search trees.
Figure 5.2.5(a) is a binary search tree, whereas figure 5.2.5(b) is not a binary search
tree.
16 16
12 20 12 20
11 14 19 11 14 19
17
13 13 17
The subtrees in a tree are unordered. The subtrees of each element in a binary
tree are ordered (i.e. we distinguish
between left and right subtrees).
There is a one-to-one mapping between general ordered trees and binary trees. So,
every tree can be uniquely represented by a binary tree. Furthermore, a forest can also
be represented by a binary tree.
Stage 1:
As a first step, we delete all the branches originating in every node except
the left most branch.
We draw edges from a node to the node on the right, if any, which is
situated at the same level.
Stage 2:
Once this is done then for any particular node, we choose its left and right
sons in the following manner:
The left son is the node, which is immediately below the given node,
and the right son is the node to the immediate right of the given node
on the same horizontal line. Such a binary tree will not have a right
subtree.
Example 1:
2 3 4 5
6 7 8 9 10 11
Solution:
2 3 4 5
6 7 8 9 10 11
6 3
7 8 4
10
11
Example 2:
1 7
2 3 8 9 10
4 5 6 11 12 13
0
Solution:
2 3 8 9 10
4 5 6 11 12 13
Stage 2 tree by using the above mentioned procedure is as follows (binary tree
representation of forest):
2 7
4 3 8
5 6 11 9
9
10
12
13
Example 3:
B F J
C D E G H K L M N
P Q
Ge n e r a l t r e e T
Solution:
1. Stage 1:
B F J
C D E G B
H
5 K L M N
P Q
Stage 2:
C F
D G J
1E0 H K
L
Bi n a rt t r e e T ’
P N
2. Suppose T is a general tree with root R and subtrees T 1, T2, ………., TM. The
preorder traversal and the postorder traversal of T are:
The tree T has the root A and subtrees T1, T2 and T3 such that:
T1 consists of nodes B, C, D and E.
T2 consists of nodes F, G and H.
T3 consists of nodes J, K, L, M, N, P and Q.
A. The preorder traversal of T consists of the following steps:
(i) Process root A.
(ii) Traverse T1 in preorder: Process nodes B, C, D, E.
3. The preorder, inorder and postorder traversals of the binary tree T’ are as
follows:
Preorder: A, B, C, D, E, F, G, H, J, K, M, P, Q, N
Inorder: C, D, E, B, G, H, F, K, L, P, Q, M, N, J, A
Postorder: E, D, C, H, G, Q, P, N, M, L, K, J, F, B, A
4. Comparing the preorder and postorder traversals of T’ with the general tree T:
We can observer that the preorder of the binary tree T’ is identical to the
preorder of the general T.
The inorder traversal of the binary tree T’ is identical to the postorder traversal
of the general tree T.
Search involves visiting nodes in a tree in a systematic manner, and may or may not
result into a visit to all nodes. When the search necessarily involved the examination of
every vertex in the tree, it is called the traversal. Traversing of a tree can be done in
two ways.
In Depth first search, we begin with root as a start state, then some successor of the
start state, then some successor of that state, then some successor of that and so on,
If depth first search reaches a state S without successors, or if all the successors of a
state S have been chosen (visited) and a goal state has not get been found, then it
“backs up” that means it goes to the immediately previous state or predecessor
formally, the state whose successor was ‘S’ originally.
A
E
ST A RT J
S B
H G GOAL
C F
K
I
Suppose S is the start and G is the only goal state. Depth first search will first visit S,
then A, then D. But D has no successors, so we must back up to A and try its second
successor, E. But this doesn’t have any successors either, so we back up to A again.
But now we have tried all the successors of A and haven’t found the goal state G so we
must back to ‘S’. Now ‘S’ has a second successor, B. But B has no successors, so we
back up to S again and choose its third successor, C. C has one successor, F. The first
successor of F is H, and the first of H is J. J doesn’t have any successors, so we back up
to H and try its second successor. And that’s G, the only goal state.
So the solution path to the goal is S, C, F, H and G and the states considered were in
order S, A, D, E, B, C, F, H, J, G.
Disadvantages:
1. It works very fine when search graphs are trees or lattices, but can get
struck in an infinite loop on graphs. This is because depth first search can
travel around a cycle in the graph forever.
To eliminate this keep a list of states previously visited, and never permit
search to return to any of them.
Breadth-first search starts at root node S and “discovers" which vertices are reachable
from S. Breadth-first search discovers vertices in increasing order of distance. Breadth-
first search is named because it visits vertices across the entire breadth.
A
E
ST A RT J
S B
H G GOAL
C F
K
I
Breadth first search finds states level by level. Here we first check all the immediate
successors of the start state. Then all the immediate successors of these, then all the
immediate successors of these, and so on until we find a goal node. Suppose S is the
start state and G is the goal state. In the figure, start state S is at level 0; A, B and C
are at level 1; D, e and F at level 2; H and I at level 3; and J, G and K at level 4.
Breadth first search does not have the danger of infinite loops as we consider states in
order of increasing number of branches (level) from the start state.
One simple way to implement breadth first search is to use a queue data structure
consisting of just a start state.
0 0 0 5
0 2 0 0
A 1 3 0 0
0 0 4 0
(3, 1) 1
(2, 2) 2
S= (3, 2) 3
(4, 3) 4
(1, 4) 5
The printed output lists the non-zero elements of S, together with their row and column
indices. The elements are sorted by columns, reflecting the internal data structure.
In large number of applications, sparse matrices are involved. One approach is to use
the linked list.
The program to represent sparse matrix:
# include <stdio.h>
# include <conio.h>
main()
{
int matrix[20][20], m, n, total_elements, total_zeros = 0, i, j;
clrscr();
printf("\n Enter Number of rows and columns: ");
scanf("%d %d",&m, &n);
total_elements = m * n;
printf("\n Enter data for sparse matrix: ");
for(i = 0; i < m ; i++)
{
for( j = 0; j < n ; j++)
{
scanf("%d", &matrix[i][j]);
if( matrix[i][j] == 0)
{
total_zeros++;
}
}
}
if(total_zeros > total_elements/2 )
{
printf("\n Given Matrix is Sparse Matrix..");
printf("\n The Representaion of Sparse Matrix is: \n");
printf("\n Row \t Col \t Value ");
for(i = 0; i < m ; i++)
{
for( j = 0; j < n ; j++)
{
if( matrix[i][j] != 0)
{
printf("\n %d \t %d \t %d",i,j,matrix[i][j]);
}
}
}
}
else
printf("\n Given Matrix is Not a Sparse Matrix..");
}
EXCERCISES
2. a. Draw all the possible binary trees that have four leaves and all the nonleaf nodes
have no children.
b. Show what would be printed by each of the following.
An inorder traversal of the tree
A postorder traversal of the tree
A preorder traversal of the tree
3. a. Draw the binary search tree whose elements are inserted in the following order:
50 72 96 94 107 26 12 11 9 2 10 25 51 16 17 95
g. Show how the tree would look after the deletion of 29, 59 and 47?
h. Show how the (original) tree would look after the insertion of nodes containing
63, 77, 76, 48, 9 and 10 (in that order).
5. Write a “C” function to count the number of leaf nodes in a binary tree.
7. Write a “C” function to compute the maximum number of nodes in any level of a
binary tree. The maximum number of nodes in any level of a binary tree is also
called the width of the tree.
8. Construct two binary trees so that their postorder traversal sequences are the
same.
9. Write a “C” function to compute the internal path length of a binary tree.
10. Write a “C” function to compute the external path length of a binary tree.
11. Prove that every node in a tree except the root node has a unique parent.
12. Write a “C” function to reconstruct a binary tree from its preorder and inorder
traversal sequences.
13. Prove that the inorder and postorder traversal sequences of a binary tree
uniquely characterize the binary tree. Write a “C” function to reconstruct a binary
tree from its postorder and inorder traversal sequences.
14. Build the binary tree from the given traversal techniques:
B. Inorder: gdhbeiafjc
Postorder: ghdiebjfca
C. Inorder: gdhbeiafjc
Level order: abcdefghij
15. Build the binary tree from the given traversal techniques:
A. Inorder: n1 n2 n3 n4 n5 n6 n7 n8 n9
Preorder: n6 n2 n1 n4 n3 n5 n9 n7 n8
B. Inorder: n1 n2 n3 n4 n5 n6 n7 n8 n9
Postorder: n1 n3 n5 n4 n2 n8 n7 n9 n6
C. Inorder: n1 n2 n3 n4 n5 n6 n7 n8 n9
Level order: n6 n2 n9 n1 n4 n7 n3 n5 n8
16. Build the binary tree for the given inorder and preorder traversals:
Inorder: EACKFHDBG
Preorder: FAEKCDHGB
1 7 10
12 15 13 14 8
11 4
5 9 2 6
16 17
2. A binary tree in which all the leaves are on the same level is called as: [ B ]
A. Complete binary tree C. Strictly binary tree
B. Full binary tree D. Binary search tree
B C
FI G UR E 1
D E F G
H I J K
7. For the Binary tree shown in fig. 1, the in-order traversal sequence is: [ C ]
A. A B C D E F G H I J K C. H D I B E A F C J G K
B. H I D E B F J K G C A D. A B D H I E C F G J K
8. For the Binary tree shown in fig. 1, the pre-order traversal sequence is: [ D ]
A. A B C D E F G H I J K C. H D I B E A F C J G K
B. H I D E B F J K G C A D. A B D H I E C F G J K
9. For the Binary tree shown in fig. 1, the post-order traversal sequence is: [ B ]
A. A B C D E F G H I J K C. H D I B E A F C J G K
B. H I D E B F J K G C A D. A B D H I E C F G J K
36 9 C ADF
C D E
D ABCEFG
25 16 E BDG
28
3
F CDG
F G
17 G FDE
11. For the figure 2 shown above, the cost of the minimal spanning tree is: [ A ]
A. 57 C. 48
B. 68 D. 32
14
2 11
FIGURE 3
1 3 10 30
7 40
13. For the figure 3, how many of the nodes have at least one sibling? [ A ]
A. 5 C. 7
B. 6 D. 8
14. For the figure 3, How many descendants does the root have? [ D ]
A. 0 C. 4
B. 2 D. 8
17. There is a tree in the box at the top of this section. What is the order of [ ]
nodes visited using a pre-order traversal?
18. There is a tree in the box at the top of this section. What is the order of [ ]
nodes visited using an in-order traversal?
A. 1 2 3 7 10 11 14 30 40 C. 1 3 2 7 10 40 30 11 14
B. 1 2 3 14 7 10 11 40 30 D. 14 2 1 3 11 10 7 30 40
19. There is a tree in the box at the top of this section. What is the order of [ ]
nodes visited using a post-order traversal?
A. 1 2 3 7 10 11 14 30 40 C. 1 3 2 7 10 40 30 11 14
B. 1 2 3 14 7 10 11 40 30 D. 14 2 1 3 11 10 7 30 40
20. What is the minimum number of nodes in a full binary tree with depth 3? [ D ]
A. 3 C. 8
B. 4 D. 15
22. Suppose T is a binary tree with 14 nodes. What is the minimum possible [ B ]
depth of T?
A. 0 C. 4
B. 3 D. 5
24. Consider the node of a complete binary tree whose value is stored in [ C ]
data[i] for an array implementation. If this node has a right child, where
will the right child's value be stored?
A. data[i+1] C. data[2*i + 1]
B. data[i+2] D. data[2*i + 2]
14
2 16 Figure 4
1 5
25. For the binary search tree shown in figure 4, Suppose we remove the root, [ D ]
replacing it with something from the left subtree. What will be the new
root?
A. 1 D. 5
B. 2 E. 16
B C G
Tr e e 2 F
D
E C
E F
I D A
G H
I J H B
Tr e e 1
J
26. Which traversals of tree 1 and tree 2, will produce the same sequence of [ C ]
node names?
A. Preorder, Postorder C. Postorder, Inorder
B. Postorder, Postorder D. Inorder, Inorder
3 7 4 7
2 6
3 6
B. D.
5 14
3 2 2 16
7 6
1 5
23
11 27
7 17 25
6 9 14 FI G UR E 5
28. For the binary search tree shown in figure 5, after deleting 23 from the [ ]
binary search tree what node will be at the root?
A. 11 C. 27
B. 25 D. 14
33. The data structure used by level order traversal of binary tree is: [ A ]
A. Queue C. linked list
B. Stack D. none of the above