2. Trees
Trees are very flexible, versatile and powerful non-liner data
structure that can be used to represent data items possessing
hierarchical relationship between the grand father and his
children and grand children as so on.
Topics Discussed in this Section:
➢ Binary Tree and its basic Terminologies
➢ Binary Tress Representation
➢ Types of Binary Tree
➢ Operations on Binary Tree
➢ Traversals of a Tree
➢ Algorithm for Evaluating an Expression Tree
➢ Variable Length Coding- Huffmann Coding (Compression)
2
3. Trees
A tree is an ideal data structure for representing hierarchical data. A tree can be
theoretically defined as a finite set of one or more data items (or nodes) such that :
1. There is a special node called the root of the tree.
2. Removing nodes (or data item) are partitioned into number of mutually
exclusive (i.e., disjoined) subsets each of which is itself a tree, are called sub
tree.
3
4. Applications
◼ Organization charts
◼ File systems
◼ Programming
environments
Computers”R”Us
Sales Manufacturing R&D
Laptops Desktops
US International
Europe Asia Canada
5. subtree
Tree Terminology
◼ Root: node without parent (A)
◼ Siblings: nodes share the same parent
◼ Internal node: node with at least one child (A, B,
C, F)
◼ External node (leaf ): node without children (E, I,
J, K, G, H, D)
◼ Ancestors of a node: parent, grandparent, grand-
grandparent, etc.
◼ Descendant of a node: child, grandchild, grand-
grandchild, etc.
◼ Depth of a node: number of ancestors
◼ Height of a tree: maximum depth of any node (3)
◼ Degree of a node: the number of its children
◼ Degree of a tree: the maximum number of its node.
A
B D
C
G H
E F
I J K
Subtree: tree consisting of a
node and its descendants
8. Binary Tree Representation
1. Sequential representation using arrays
2. Linked list representation
Sequential representation using arrays:
▪ An array can be used to store the nodes of a binary tree.
The nodes stored in an array of memory can be accessed
sequentially.
• Suppose a binary tree T of depth d. Then at most 2d+1 – 1
nodes can be there in T.(i.e., SIZE = 2d+1 – 1 ) So the
array of size “SIZE” to represent the binary tree.
• Consider a binary tree in Figure of depth 2. Then SIZE =
23 – 1 = 7. Then the array A[7] is declared to hold the
nodes.
8
9. Binary Tree Representation
9
◼ To perform any operation often we have to identify the father, the left child and right
child of an arbitrary node.
1. The father of a node having index n can be obtained by (n – 1)/2. For example to find the
father of D, where array index n = 3. Then the father nodes index can be obtained
= (n – 1)/2
= 3 – 1/2
= 2/2
= 1
i.e., A[1] is the father D, which is B.
2. The left child of a node having index n can be obtained by (2n+1). For example to find the
left child of C, where array index n = 2. Then it can be obtained by
= (2n +1)
= 2*2 + 1
= 4 + 1
= 5
i.e., A[5] is the left child of C, which is NULL. So no left child for C.
10. Binary Tree Representation
10
3. The right child of a node having array index n can be obtained by the formula (2n + 2). For
example to find the right child of B, where the array index n = 1. Then
= (2n + 2)
= 2*1 + 2
= 4
i.e., A[4] is the right child of B, which is E.
4. If the left child is at array index n, then its right brother is at (n + 1). Similarly, if the right
child is at index n, then its left brother is at (n – 1).
◼ The array representation is more ideal for the complete binary tree.
11. Binary Tree Representation
◼ LINKED LIST REPRESENTATION
A node consists of three fields such as :
(a) Left Child (LChild)
(b) Information of the Node (Info)
(c) Right Child (RChild)
11
12.
13. Types of Binary Tree
1. Binary Tree
2. Strictly Binary Tree
3. Complete Binary Tree
13
15. Types of Binary Tree
◼ The tree is said to be strictly binary tree, if every non-leaf made in a
binary tree has non-empty left and right sub trees.
◼ Astrictly binary tree with n leaves always contains 2n– 1 nodes.
◼ That is every node in the strictly binary tree can have either no children
or two children.
◼ They are also called 2-tree or extended binary tree.
15
16. Types of Binary Tree
◼ Acomplete binary tree at depth ‘d’is the strictly binary tree, where all
the leaves are at level d.
Some Facts :
• Abinary tree with n nodes, n > 0, has exactly n – 1 edges.
• Abinary tree of depth d, d > 0, has at least d and atmost 2d+1– 1 nodes in it.
• If a binary tree contains n nodes at level l, then it contains at most 2n
nodes at level l + 1.
• A complete binary tree of depth d is the binary tree of depth d contains
exactly 2l nodes at each level l between 0 and d.
16
17. Types of Binary Tree
◼ Left Skewed Trees Right Skewed Trees
17
18. Operations on Binary Tree
18
1. Create a Root Node of a tree
2. Creating a left child of a tree
3. Creating a right child of a tree
4. Traversing a Binary Tree
5. Evaluating an expression Tree
6. Huffmann coding (Application of trees in Compression)
7. Finding the depth of a tree
8. Counting the number of nodes in a tree
9. Counting the leaf nodes in a tree.
19. Operations on Binary Tree
19
1. Create a Root Node of a tree
NODE maketree (int x)
{
NODE p;
p =(NODE *) malloc((size of (NODE));
p ->info = x;
p -> left= NULL;
p -> right = NULL;
return (p);
}
20. Operations on Binary Tree
20
2. Creating a left child of a tree
setleft(p,x) sets a node with contents x as the left son of
node(p).
void setleft (NODE p, int x)
{
if(p==NULL)
cout<<“ Void Insertion”;
else if (p->left !=NULL)
cout<<“Invalid Insertion”;
else
p->left = maketree(x);
}
21. Operations on Binary Tree
21
3. Creating a right child of a tree
setright(p,x) sets a node with contents x as the left son of
node(p).
void setright (NODE p, int x)
{
if(p==NULL)
cout<<“ Void Insertion”;
else if (p->right!=NULL)
cout<<“Invalid Insertion”;
else
p->right = maketree(x);
}
22. 4. Traversals of a tree
22
◼ It is a way in which each node in the tree is visited exactly once in a
systematic manner.
◼ There are three standard ways of traversing a binary tree. They are:
1. Pre Order Traversal (Node-left-right)
2. In order Traversal (Left-node-right)
3. Post Order Traversal (Left-right-node)
38. Traversals of a tree
1. Pre Order Traversal (Node-left-right)
◼ To traverse a non-empty binary tree in pre order following steps one to
be processed
1. Visit the root node
2. Traverse the left sub tree in preorder
3. Traverse the right sub tree in preorder
void preorder (Node * Root)
{
if (Root != NULL)
{
cout<<Root → Info);
preorder(Root → L child);
preorder(Root → R child);
}
}
38
39. Traversals of a tree
1. Pre Order Traversal (Node-left-right)
◼ To traverse a non-empty binary tree in pre order following steps one to
be processed
1. Visit the root node
2. Traverse the left sub tree in preorder
3. Traverse the right sub tree in preorder
void preorder (Node * Root)
{
if (Root != NULL)
{
cout<<Root → Info);
preorder(Root → L child);
preorder(Root → R child);
}
} The preorder traversal of a binary tree isA, B, D, E, H, I, C, F, G, J.
39
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54. Traversals of a tree
2. In order Traversal (Left-node-right)
◼ The in order traversal of a non-empty binary tree is defined as
follows :
1. Traverse the left sub tree in order
2. Visit the root node
3. Traverse the right sub tree in order
void inorder (NODE *Root)
{
if (Root != NULL)
{
inorder(Root → L child);
cout<<Root -> info;
inorder(Root → R child);
}
}
54
55. Traversals of a tree
2. In order Traversal (Left-node-right)
◼ The in order traversal of a non-empty binary tree is defined as
follows :
1. Traverse the left sub tree in order
2. Visit the root node
3. Traverse the right sub tree in order
void inorder (NODE *Root)
{
if (Root != NULL)
{
inorder(Root → L child);
cout<<Root -> info;
inorder(Root → R child);
}
}
The in order traversal of a binary tree is D, B, H, E, I,A, F, C, J, G.
55
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70. Traversals of a tree
3. Post Order Traversal (Left-right-node)
◼ The post order traversal of a non-empty binary tree can be defined as :
1. Traverse the left sub tree in post order
2. Traverse the right sub tree in post order
3. Visit the root node
void postorder (NODE *Root)
{
if (Root != NULL)
{
postorder(Root → Lchild);
postorder(Root → Rchild);
cout<<Root -> info;
}
}
70
71. Traversals of a tree
3. Post Order Traversal (Left-right-node)
◼ The post order traversal of a non-empty binary tree can be defined as :
1. Traverse the left sub tree in post order
2. Traverse the right sub tree in post order
3. Visit the root node
void postorder (NODE *Root)
{
if (Root != NULL)
{
postorder(Root → Lchild);
postorder(Root → Rchild);
cout<<Root -> info;
}
}
The post order traversal of a binary tree is D, H, I, E, B, F, J, G, C,A
71
73. 5. Algorithm for Evaluating an Expression Tree
• An ordered tree may be used to represent a general
expressions, is called expression tree.
• Nodes in one expression tree contain operators and
operands.
• E = (a + b) * (c / (d – e)) )
73
74. Algorithm for Evaluating an Expression Tree
74
#define OPERATOR 0
#define OPERAND 1
Struct node{
short int type;
union{
char ch;
float num;
}info;
struct node *left;
struct node *right;
}
typedef struct node *NODE;
75. Algorithm for Evaluating an Expression Tree
75
The function oper checks that its first argument is valid operator and if it is,
determines the results of its operation on the next two arguments.
double oper (int symb, double op1, double op2)
{
switch(symb){
case ‘+’: return (op1 + op2);
case ‘-’: return (op1 - op2);
case ‘*’: return (op1 * op2);
case ‘/’: return (op1 / op2);
case ‘$’: return (pow(op1 ,op2));
default : cout<<“ILLEGALOPERATION”;
}
}
76. Algorithm for Evaluating an Expression Tree
76
evalbintree- accepts a pointer to tree and returns the value of the
expression represented by tree.
float evalbintree (NODE *tree)
{
double op1, op2;
char symb;
if (tree->type == OPERAND)
return (tree-> num);
else
{ op1= evalbintree(tree->left);
op2= evalbintree(tree->right);
symb= tree ->ch;
return(oper(symb,op1,op2));
}
}
95. 6. Huffmann coding (Application of trees in
Compression)
95
▪ Huffman coding is a compression technique used to reduce the number
of bits needed to send or store a message.
▪ It is based on the idea of ‘Variable-length encoding’ that says the size of
the characters should be different such that frequently-appearing letters
should have shorter bit representations and less common letters should
have longer representations.
▪ Morse code employs the same idea, where characters that are used more
frequently such as ‘A’ ( ._ ) and ‘T’ ( _ ) have smaller code length than
characters like ‘C’( _._. ) and ‘X’ ( _.._ ) which are use less often.
97. ◼ List all distinct characters along
with their frequencies:
98. ◼ Rearrange them in descending order of their
frequencies:
◼ Create a new node with the value being the sum of two smallest nodes.
◼ Add this new node to the list and set the smallest two nodes as left and
right child of this new node (and delete them from the list).
◼ Rearrange and repeat until all the nodes are part of a common tree.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109. ◼ Label every left hand ‘0’, and every right hand ‘1’
110. ◼ Read the values on the path between the root
and the leaf nodes to find the Huffman code for
each character
111. ◼ If the string ‘MISSISSIPPI_RIVER’ were to coded using 8-bit
ASCII values, the size of the string would be 17 characters * 8 bit
= 136 bits.
◼ Using the Huffman codes derived from the Huffman tree,
‘MISSISSPPI_RIVER’ translates to
1110000101000101001001000011011010011111100101, which
is 46 bits, and hence is shorter than theASCII coded counterpart.
112. How does Huffman Coding work?
Suppose the string below is a message to be sent over a network.
113.
114.
115.
116.
117.
118.
119. Suppose we have the following message to
encode: "ABRACADABRA".
120. Suppose we have the following message to
encode: "ABRACADABRA".
•A: 5 times
•B: 2 times
•R: 2 times
•C: 1 time
•D: 1 time
121. Suppose we have the following message to
encode: "ABRACADABRA".
•A: 5 times
•B: 2 times
•R: 2 times
•C: 1 time
•D: 1 time
122. Suppose we have the following message to
encode: "ABRACADABRA".
•A: 5 times
•B: 2 times
•R: 2 times
•C: 1 time
•D: 1 time
123. Suppose we have the following message to
encode: "ABRACADABRA".
•A: 1
•B: 01
•R: 00
•C: 100
•D: 101
Encode the Message Using the assigned codes, encode the message
"ABRACADABRA":
Original Message: ABRACADABRA Encoded Message:
100010001011001001011001001
Encoded Message: 100010001011001001011001001
Decoded Message: ABRACADABR
124. A file contains the following characters with the frequencies as shown. If Huffman
Coding is used for data compression, determine-
1.Huffman Code for each character
2.Average code length
3.Length of Huffman encoded message (in bits)
125.
126.
127.
128.
129.
130.
131.
132.
133.
134. 7. Finding the depth of a tree
13
4
If( t1>t2)
{
dep=t1- 1;
cout<<“depth is:” +dep;
}
else
{
dep=t2- 1;
cout<<“depth is:” +dep;
}
Void depth(struct tree *p)
{
if(p->left!=NULL)
{
t1++;
depth(p->left);
}
if(p->right!=NULL)
{
t2++;
depth(p->right);
}
}
135. 8. Counting the number of nodes in a tree
13
5
int i =1;
void count_node(struct tree *p)
{
if(p!=NULL)
{
if ( p->left !=NULL)
{
i++;
count-node(p->left);
}
if ( p->right !=NULL)
{
i++;
count-node(p->right);
}
}
}
136. 9. Counting the leaf nodes in a tree.
13
6
int total =0;
void count_leave(struct tree *p)
{
if(p!=NULL)
{
if (( p->left ==NULL) && (p->right ==NULL) )
total ++;
else
{
count_leave(p->left);
count_leave(p->right);
}
}
}
137. Binary Search Tree
Binary Search Tree is a binary tree, which is either empty or satisfies the following
properties :
1. Every node has a value and no two nodes have the same value (i.e., all the
values are unique).
2.If there exists a left child or left sub tree then its value is less than the value of
the root.
3.The value(s) in the right child or right sub tree is larger than the value of the
root node.
The operations performed on binary tree can also be applied to Binary Search Tree
(BST). Few other operations performed on BST :
1. Inserting a node
2. Searching a node
3. Deleting a node
13
7
138. Binary Search Tree
1. Inserting a node
5. Else If (DA
TA> ROOT → Info)
(a) ROOT = ROOT → Rchild
13
8
(b) GoTo Step 4
6. If (DA
TA< ROOT → Info)
(a) ROOT → LChild = NEWNODE
7. Else If (DA
TA> ROOT → Info)
(a) ROOT → RChild = NEWNODE
8. Else
(a) Display (“DUPLICATE NODE”)
(b) EXIT
9. NEW NODE → Info = DATA
10. NEW NODE → LChild = NULL
11. NEW NODE → RChild = NULL
12. EXIT
The tree must be searched to determine where the
node is to be inserted.
ALGORITHM
NEWNODE is a pointer variable to hold the address
of the newly created node. DATA
is the information to be pushed.
1. Input the DATAto be pushed and ROOT node of
the tree.
2. NEWNODE = Create a New Node.
3. If (ROOT == NULL)
(a) ROOT=NEW NODE
4. Else If (DA
TA< ROOT → Info)
(a) ROOT = ROOT → Lchild
(b) GoTo Step 4
139. Binary Search Tree
2. Searching a node
49
Searching a node was part of the operation performed during insertion.
Algorithm to search as element from a binary search tree is given below.
ALGORITHM
1.Input the DATA to be searched and assign the address of the root node to
ROOT.
2. If (DA
TA== ROOT → Info)
(a) Display “The DA
TAexist in the tree”
(b) GoTo Step 6
3. If (ROOT == NULL)
(a) Display “The DA
TAdoes not exist”
(b) GoTo Step 6
4. If(DA
TA> ROOT→Info)
(a) ROOT = ROOT→RChild
(b) GoTo Step 2
5. If(DA
TA< ROOT→Info)
(a) ROOT = ROOT→Lchild
(b) GoTo Step 2
140. Binary Search Tree
14
0
3. Deleting a node
◼ First search and locate the node to be deleted. Then any one of the following
conditions arises :
1. The node to be deleted has no children
2. The node has exactly one child (or sub tress, left or right sub tree)
3. The node has two children (or two sub tress, left and right sub tree)
◼ Suppose the node to be deleted is N. If N has no children then simply delete the
node and place its parent node by the NULL pointer.