SlideShare a Scribd company logo
Tree
1
By:
Dabal Singh Mahara
2017
Unit – 6 Tree
Contents Hours Marks
a. Concept and definition
b. Binary tree
c. Introduction and application
d. Operations
e. Types of binary tree
 Complete binary tree
 Strictly binary tree
 Almost complete binary tree
f. Tree traversal
 Pre-order traversal
 In-order traversal
 Post-order traversal
g. Binary search tree
 searching
 insertion
 deletion
h. Expression Tree
i. Huffman algorithm
j. AVL Trees
7 9
2
Introduction
• A tree is an abstract model of a hierarchical structure that consists of
nodes with a parent-child relationship.
• A tree is a finite set of data items or nodes such that:
 There is a special data-item called the root of the tree
 Its remaining data items are partitioned into mutually exclusive sub-sets, each of
which itself is a tree, called sub-trees.
Characteristics of trees
 Non-linear data structure
 Combines advantages of an ordered array
 Searching as fast as in ordered array
 Insertion and deletion as fast as in linked list
4
Application
 Directory structure of a file store
 Structure of arithmetic expressions
 Hierarchy of an organization
5
Some Key Terms
Degree of a node:
• The degree of a node is the number of children of that node. In above
tree , degree(A) = 2.
Degree of a Tree:
• The degree of a tree is the maximum degree of nodes in a given tree. In
the above tree, maximum degree of nodes is 2, thus the degree of the
tree is 2.
Path:
• It is the sequence of consecutive edges from source node to destination
node. There is a single unique path from the root to any node.
6
Some Key Terms
 Height of a node:
The height of a node is the maximum path length from that node to a leaf
node. A leaf node has a height of 0.
 Height of a tree:
The height of a tree is the height of the root.
 Depth of a node:
Depth of a node is the path length from the root to that node. The root node
has a depth of 0.
7
Some Key Terms
Level of a node:
The level of a node is 0, if it is root; otherwise it is one more than its
parent.
Depth of a tree:
Depth of a tree is the maximum level of any leaf in the tree. This is equal
to the longest path from the root to any leaf.
8
• A is the root node
• B is the parent of E and F
• D is the sibling of B and C
• E and F are children of B
• E, F, G, D are external nodes or leaves
• A, B, C are internal nodes
• Depth of F is 2
• the height of tree is 2
• the degree of node A is 3
• The degree of tree is 3
Illustration
9
Binary Trees
 A binary tree is 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 right sub-trees of the original tree. A left or right sub tree
can be empty.
 Each element of a binary tree is called a node of the tree. The
following figure shows a binary tree with 9 nodes where A is the
root.
10
Binary Tree
11
Properties of Binary Trees
 If a binary tree contains m nodes at level l , it
contains at most 2m nodes at level l + 1.
 Since a binary tree can contain at most 1 node at
level 0 (the root), it contains at most 2l nodes at
level l.
12
Types of Binary Trees
• Strictly binary tree
• Almost complete binary tree
• Complete binary tree
13
 If every non-leaf node in a binary tree has non-empty left and right sub-trees, then
such a tree is called a strictly binary tree.
Strictly binary tree
 The following tree is not strictly binary tree, Since node E has a left son but not
a right son.
14
 A strictly binary tree of depth d is called complete binary
tree if all of whose leaves are at level d.
 A complete binary tree with depth d has 2d leaves and 2d -1
non-leaf nodes (internal).
Complete binary tree:
Example: In this tree d = 3,
therefore, leaves = 23 = 8 Internal nodes = 23 -1 = 7
15
A binary tree of depth d is an almost complete binary tree if:
i. Any node at level less than d-1 has two sons.
ii. For any node in the tree with a right descendant at level d, the node must
have a left son and every left descendant of the node is either a leaf at level
d or has two sons.
Almost complete binary tree:
16
B
J
G
F
C
I
ED
H
A
K
Level 0
Level 1
Level 2
Level 3
• This tree is not almost complete binary tree because it does not satisfy
condition ii.
• That is, node A has right descendent at level 3 ( J or K), but it has left
descendent leaf node at level 2 (node E).
17
Operations on Binary Tree
• father(n,T): Return the parent node of the node n in tree T. If n is the
root, NULL is returned.
• LeftChild(n,T): Return the left child of node n in tree T. Return NULL if
n does not have a left child.
• RightChild(n,T): Return the right child of node n in tree T. Return NULL
if n does not have a right child.
• Info(n,T): Return information stored in node n of tree T (ie. Content of a
node).
• Sibling(n,T): return the sibling node of node n in tree T. Return NULL if
n has no sibling.
18
Operations on Binary Tree
• Root(T): Return root node of a tree if and only if the tree is nonempty.
• Size(T): Return the number of nodes in tree T
• MakeEmpty(T): Create an empty tree T
• SetLeft(S,T): Attach the tree S as the left sub-tree of tree T
• SetRight(S,T): Attach the tree S as the right sub-tree of tree T.
• Preorder(T): Traverses all the nodes of tree T in preorder.
• postorder(T): Traverses all the nodes of tree T in postorder
• Inorder(T): Traverses all the nodes of tree T in inorder.
19
Binary Tree Representation
• Array Representation
– An array is used to store the nodes of the binary tree.
– Nodes stored in the array are accessed sequentially, root is at index
0 and then left child and right child are stored.
– To store the elements of the binary tree of depth d, declare the array
of size 2d+1 -1, i.e. the total number of nodes of complete binary tree
and store the elements level wise.
– If root is at i then left child is t 2i+1 and right child is at 2i+2.
20
B
J
G
F
C
I
ED
H
A0
1
2
4
7
5
14
6
3
10
• Declare array of size 2 3+1 -1 = 15
Char a[15]
A B C D E F G H I J
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
21
Array Representation
Linked Representation of Binary Tree
• It is the most popular way to present a binary tree. Each element is
represented by a node that has two link fields (leftChild and rightChild) plus
an element field. Each binary tree node is represented as an object whose
data type is binaryTreeNode .
• The space required by an n node binary tree is: n * sizeof(binaryTreeNode)
C representation for Binary tree
struct binaryTreeNode
{
int info;
struct binaryTreenode *left;
struct binaryTreenode *right;
};
struct binaryTreenode *root=NULL;
22
The given tree can be represented in linked list as
given below.
23
 The tree traversal is a way in which each node in the
tree is visited exactly once in a symmetric manner.
 There are three popular methods of traversal
i. Pre-order traversal
ii. In-order traversal
iii. Post-order traversal
Tree traversal
24
1. Pre-order traversal:
The preorder traversal of a nonempty binary tree is defined as
follows:
i. Visit the root node
ii. Traverse the left sub-tree in preorder
iii. Traverse the right sub-tree in preorder
The preorder traversal output of the given tree
is: A B D H I E C F G
The preorder is also known as depth first order.
C function for preorder traversing:
void preorder(struct bnode *root)
{
if(root!=NULL)
{
printf(“%c”, root->info);
preorder(root->left);
preorder(root->right);
}
}
25
The inorder traversal of a nonempty binary tree is defined as follows:
i. Traverse the left sub-tree in inorder
ii. Visit the root node
iii. Traverse the right sub-tree in inorder
The inorder traversal output of the given tree
is: H D I B E A F C G
C function for inorder traversing:
void inorder(struct binaryTreenode *root)
{
if(root!=NULL)
{
inorder(root->left);
printf(“%c”, root->info);
inorder(root->right);
}
}
2. In-order traversal:
26
3. Post-order traversal:
The post-order traversal of a nonempty binary tree is defined as follows:
i. Traverse the left sub-tree in post-order
ii. Traverse the right sub-tree in post-order
iii. Visit the root node
C function for post-order traversing:
void post-order(struct bnode *root)
{
if(root!=NULL)
{
post-order(root->left);
post-order(root->right);
printf(“%c”, root->info);
}
}
The post-order traversal output of the given tree
is: H I D E B F G C A
27
Q. Design a binary tree whose traversal sequences are given below:
Pre-order: CPRBLOEMATIK
In-Order: BRLPEOMCTAIK
Solution:
Since preorder traverses from root of the tree, C is root of the tree.
The { B, R, L, P, E, O, M} and {T, I, A, K } are respectively left and right sub
tree . (from inorder sequence)
C
T, A,
I, K
B, R, L,
P, E, O,
M
28
C
I, KB, R, L,
P
E, O, M
A
T
• Similarly, for left sub tree { B, R, L, P, E, O, M}, root is P ( from preorder sequence)
and {B, R, L} is left sub-tree and {E, O, M} is right sub-tree. ( From inorder sequence)
• For right sub-tree {T, A, I, K}, A is the root. ( from preorder sequence)
T is left sub-tree and {I, K } is right sub-tree.
29
• Similarly, R is root for sub-tree {B, R, L} ( from preorder sequence)
B is left child and L right child of R ( from inorder sequence)
• O is root for sub-tree {E, O, M} (from preorder sequence)
E is left child and M is right child of O (from inorder sequence)
• In the same way, I is root and K is right child for sub-tree { I, K }
C
P A
TO I
KL M
R
EB
30
Q. A binary tree T has 12 nodes. The in-order and post-order traversals of T yield the
following sequence of nodes:
In-order : VPNAQRSOKBTM
Post-order : VANRQPBKOMTS
Construct the Binary tree T showing each step. Explain how you can arrive at
solution in brief.
Solution:
Since post-order traversal visits all nodes in left sub-tree , right sub-tree and root
recursively, the last node in the sequence is root of the tree. That is, S is the root.
In-order traversal visits the nodes in Left child, root and right child in recursive way, {
V,P, N,A, Q, R} is left sub-tree and {O, K, B, T, M} is the right sub tree.
S
O, K,
B, T,
M
V, P, N,
A, Q, R
Step -1:
31
• Step -2: The root of { V, P, N, A, Q, R} is P obtained from
postorder sequence. Left subtree and right sub trees are {v}
and {N, A, Q, R} obtained from inorder sequence.
• Similarly, for { O, K, T, B, M} , root is T and left sub tree {O, K, B}
and right sub tree is {M}.
32
S
O, K, B
P T
MV
N, A, Q, R
O
S
K, B
P
N, A
T
MV
Q
R
Step -3: In the same way, root and sub trees are
obtained.
33
S
P T
MV Q
R
Step -4: The final tree is given below.
O
K
B
A
N
• Thus, root of the tree is obtained from post-order sequence scanning
from right to left and left and right sub-trees of corresponding root are
obtained from inorder sequence.
34
• An important application of binary trees is their use in searching.
• A binary search tree (BST) is a binary tree that is either empty or in
which every node contains a key (value) and satisfies the following
conditions:
i. All keys in the left sub-tree of the root are smaller than the key in
the root node.
ii. All keys in the right sub-tree of the root are greater than the key in
the root node.
iii. The left and right sub-trees of the root are again binary search
trees .
Binary search tree(BST)
35
Binary Search Trees
1 4
2
3
8
6
1 4
2
3
8
6
7
• The tree on the left is a binary search tree, but the tree on
the right is not.
36
• Given the following sequence of numbers, 14, 15, 4, 9, 7, 18, 3, 5, 16, 20,
17, 5
• The following binary search tree can be constructed:
14
4
9
15
7
5 17
2016
3 18
• The inorder traversal of BST gives the sorted sequence in ascending order.
So, inorder traversal of above BST is: 3, 4, 5, 7, 9, 14, 15, 16, 17, 18, 20.
37
Following operations can be done in BST:
 Search(k, T): Search for key k in the tree T. If k is found in some node
of tree then return true otherwise return false.
 Insert(k, T): Insert a new node with value k in the info field in the tree
T such that the property of BST is maintained.
 Delete(k, T):Delete a node with value k in the info field from the tree T
such that the property of BST is maintained.
 FindMin(T), FindMax(T): Find minimum and maximum element from
the given nonempty BST.
Operations on Binary search tree(BST):
38
struct bstnode
{
int info; //Declaring an info field
struct bstnode *left; // left child pointer
struct bstnode *right; // right child pointer
};
Structure of BST node
Struct bstnode *root = NULL;
39
To find if any node of a BST contains an element equal to target:
1. Set curr to the BST’s root.
2. Repeat:
2.1. If curr is null:
2.1.1. Terminate with answer none.
2.2. Otherwise, if target is equal to curr’s element:
2.2.1. Terminate with answer curr.
2.3. Otherwise, if target is less than curr’s element:
2.3.1. Set curr to curr’s left child.
2.4. Otherwise, if target is greater than curr’s element:
2.4.1. Set curr to curr’s right child.
3. end
BST search algorithm :
40
C function for BST searching:
void BinSearch(struct bstnode *root , int key)
{
if(root == NULL)
{
printf(“The number does not exist”);
}
else if (key == root->info)
{
printf(“The searched item is found”):
}
else if(key < root->info)
BinSearch(root->left, key);
else
BinSearch(root->right, key);
} 41
• To insert a new item in a tree, we must first verify that its key is different from those of existing
elements. To do this a search is carried out. If the search is unsuccessful, then item is inserted.
• Idea: To insert a new element into a BST, proceed as if searching for that element. If the
element is not already present, the search will lead to a null link. Replace that null link by a
link to a leaf node containing the new element.
Insertion of a node in BST:
15
9
13
12
10
18
20
22
25
Insertion of element 13
42
To insert the element elem into a BST:
1. Set parent to null, and set curr to the BST’s root.
2. Repeat:
2.1. If curr is null:
2.1.1. Replace the null link from which curr was taken
(either the BST’s root or parent’s left child or parent’s right child) link to a
newly-created leaf node with element elem.
2.1.2. Terminate.
2.2. Otherwise, if elem is equal to curr’s element:
2.2.1. Terminate.
2.3. Otherwise, if elem is less than curr’s element:
2.3.1. Set parent to curr, and set curr to curr’s left child.
2.4. Otherwise, if elem is greater than curr’s element:
2.4.1. Set parent to curr, and set curr to curr’s right child.
3.End
BST insertion algorithm :
43
C function for BST insertion:
Struct bstnode * insert(struct bstnode *root, int item)
{
if(root=NULL)
{
root=(struct bstnode*)malloc (sizeof(struct bnode));
root->left = root->right=NULL;
root->info = item;
}
else if ( item == root->info)
{
printf("n Duplicate not allowed.");
return root;
}
else
{
if(item<root->info)
root->left=insert(root->left, item);
else
root->right=insert(root->right, item);
}
}
44
While deleting a node from BST, there may be three cases:
1. The node to be deleted may be a leaf node:
In this case simply delete a node and set null pointer to its parents those side
at which this deleted node exist.
Deleting a node from the BST:
45
2. The node to be deleted has one child:
In this case the child of the node to be deleted is appended to its
parent node. Suppose node to be deleted is 18
Delete(18)
46
3. The node to be deleted has two children:
In this case node to be deleted is replaced by its in-order successor node.
That is, the node to be deleted is either replaced by its right sub-trees
leftmost node or its left sub-trees rightmost node.
Suppose node to deleted is 12. Find minimum element in the right sub-
tree of the node to be removed. In current example it is 19.
Delete(12)
47
1. start
2. if a node to be deleted is a leaf node at left side then simply
delete and set null pointer to it's parent's left pointer.
3. If a node to be deleted is a leaf node at right side then
simply delete and set null pointer to it's parent's right
pointer.
4. if a node to be deleted has one child then connect it's child
pointer with it's parent pointer and delete it from the tree.
5. if a node to be deleted has two children then replace the
node being deleted either by
a. right most node of it's left sub-tree or
b. left most node of it's right sub-tree.
6. End
48
General algorithm to delete a node from a BST
Delete a node in BST
struct bstnode *delnode(struct bstnode *root, int
item)
{
struct bstnode *temp;
if(root==NULL)
{
printf(“Empty tree”);
return;
}
else if(item<root->info)
root->left=delnode(root->left, item);
else if(item>root->info)
root->right=delnode(root->right, item);
else if(root->left!=NULL && root->right!=NULL)
//node has two children
{
temp=findmin(root->right);
root->info=temp->info;
root->right=delnode(root->right, root->info);
}
else
{
temp=root;
if(root->left==NULL)
root=root->right;
else if(root->right==NULL)
root=root->left;
free(temp);
}
return(root);
}
49
struct bstnode * findmin(struct bstnode * root)
{
if(root==NULL)
return NULL;
else if(root->left ==NULL)
return head;
else
return(findmin(root->left));
}
Findmin Function
50
Expression Tree
• An expression tree is a strictly binary tree in which leaf node contains
operands and non-leaf node contain operators.
• Root nodes contain the operators that is applied to the result of left and
right sub trees.
• The operators, constants, and variables are arranged in such a way that
an inorder traversal of the tree produces the original expression without
parentheses.
• Example: An expression tree of an expression (a + b *c ) +((c*e +f) *g)
*a
+ *
g+
f
*
ec
c
+
b
51
Exercise
• Construct an expression tree of an expression:
(a + b ) /((c-d) *e)
52
Expression Tree Examples
Inorder Traversal ResultExpression TreeExpression
a + 3(a+3)
3+4*5-9+63+(4*5-(9+6))
log xlog(x)
n !n!
+
3a
+
-3
*
54
+
69
log
x
!
n
53
Constructing an Expression Tree From Postfix
Expression
Algorithm
1. Read the expression one symbol at a time.
2. If the symbol is an operand, we create a one-node tree and push a pointer
to it onto a stack.
3. If the symbol is an operator, we pop pointers to two trees T1 and T2 from
the stack (T1 is popped first) and form a new tree whose root is the
operator and whose left and right children point to T2 and T1, respectively.
A pointer to this new tree is then pushed onto the stack.
54
• Input: ab+cde+**
 The first two symbols are operands, so we create
one-node trees and push pointers to them onto a
stack. For convenience, we will have the stack
grow from left to right in the diagrams. 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 a one-
node tree is created and a pointer to the
corresponding tree is pushed onto the stack.
a b
+ c d e
55
Example: Constructing an Expression Tree
Constructing an Expression Tree
a b
+ c
• Now a ‘+’ is read, so two trees are merged.
d e
+
a b
+
c
 Continuing, a ‘*’ is read, so we pop two tree pointers and form a new
tree with a ‘*’ as root.
d e
+
*
56
Constructing an Expression Tree
a b
+
c
 Finally, the last symbol is read, two trees are merged, and a pointer to the final
tree is left on the stack.
d e
+
*
*
Exercise: Construct an expression from postfix expression:
AB+C*DC--FG+$ 57
• Proposed by Dr. David A. Huffman at MIT in 1952
– “A Method for the Construction of Minimum Redundancy Codes”
• Huffman coding is a form of statistical coding
– more frequently used symbols have shorter code words
– Not all characters occur with the same frequency!
– Yet all characters are allocated the same amount of space
– 1 char = 1 byte, be it e or x
• Huffman coding is a technique used to compress files for transmission
• Works well for text and fax transmissions
The Huffman Coding
58
• Huffman codes is text compression method, which relies on the
relative frequency (i.e., the number of occurrences of a symbol)
with which different symbols appear in a text
• Uses extended binary trees
• Variable-length codes that satisfy the property, where no code is a
prefix of another
• Huffman tree is a binary tree with minimum weighted external path
length for a given set of frequencies (weights).
59
Huffman Code
Huffman Algorithm
1.Initially, each symbol is one node tree by itself. That is, there is
forest of n nodes each labelled with symbol and weight.
2.Repeat while n>1
i. Select the two trees T1 and T2 with minimum weights from the forest.
ii. Merge T1 and T2 to form T3 with weight sum of both trees.
iii. Insert T3 into the forest.
3. Assign 0 to each left path of tree and 1 to right path. The code for
each symbol is obtained by collecting bits on the paths from root
to the leaf node labelled with the symbol.
60
Example: 1 Let us take any four characters and their frequencies as follows:
Char frequency
E 10
T 7
O 5
A 3
• Without using Huffman coding, these four characters can be represented by
using two bits as: 00 -> E, T ->01, O ->10 and A-> 11. This is fixed length coding.
So, bits required to encode all the characters in the above message will be:
( 10 +7+5+3) * 2 = 50 bits
• Huffman coding technique uses variable length code depending upon the
frequency of characters used in the text. It's coding technique is as follows:
First sort the characters by their frequency in non-decreasing order.
Char frequency
A 3
O 5
T 7
E 10 61
1. Create a forest of one node trees for each character as:
A : 3 O : 5 T : 7 E: 10
2. Merge two minimum trees as a single tree and add it to the forest in the
order.
T1 : 8
O: 5A : 3
T : 7 E: 10
3. Repeat step 2 again.
T2 : 15
T : 7
T1 : 8
O: 5A : 3
E: 10
62
4. Repeat the step 2 again.
T3: 25
E: 10
T2 : 15
T : 7
T1 : 8
O: 5A : 3
T3: 25
E: 10
T2 : 15
T : 7
T1 : 8
O: 5A : 3
5. Assign 0 to left path and 1 to right path in the tree.
0
0
0
1
1
1
This tree is called Huffman tree.
63
Now the code for each characters are as obtained by collecting
the bits from root to the character node. The codes are:
Char code frequency
E 0 10
T 10 7
A 110 3
O 111 5
Therefore, total number of bits required = 10* 1 +7 *2 + 3 *3 + 5
*3 =48 bits
The space saved = (50-48)/50 *100 % = 4 %
64
Huffman Code
Example: 2
Let us take any four characters and their frequencies as follows:
Char frequency
a 10
e 15
i 12
s 3
t 4
Sp (space) 13
nl (new line) 1
Fixed Length Format: These 7 characters can be represented by three bits.
So, total number of bits = (10+15+12+3+4+13+1) * 3 = 174
Using Huffman Coding
First sort the characters by their frequency in non-decreasing order.
Char frequency
nl (new line) 1
s 3
t 4
a 10
i 12
Sp (space) 13
e 15
65
1. Create a forest of one node trees for each character as:
2. Merge two minimum trees as a single tree and add it to the forest in the
order.
T1 : 4
S : 3
nl :
1
3. Repeat step 2 again.
nl :
1
s:
3
t :
4
a:
10
i:
12
sp:
13
e:
15
t :
4
a:
10
i:
12
sp:
13
e:
15
a:
10
i: 12
sp:
13
e:
15
T2 : 8
T1 : 4
S : 3
nl :
1
t :
4
66
4. Repeat step 2 again.
i: 12 sp: 13 e: 15
T2 : 8
T1 : 4
S : 3nl : 1
t : 4
T3 : 18
a : 10
5. Repeat step 2 again.
e: 15 T4:
25
sp: 13i: 12
T2 : 8
T1 : 4
S : 3nl : 1
t : 4
T3 : 18
a : 10
67
6. Repeat step 2 again.
sp: 13
T4:
25
i: 12 T2 : 8
T1 : 4
S : 3nl : 1
t : 4
T3 : 18
a : 10
e: 15
T5: 33
68
sp: 13
T4:
25
i: 12 T2 : 8
T1 : 4
S : 3nl : 1
t : 4
T3 : 18
a : 10
e: 15
T5: 33
T6: 58
7. Repeat step 2 again.
69
sp: 13
T4:
25
i: 12 T2 : 8
T1 : 4
S : 3nl : 1
t : 4
T3 : 18
a : 10
e: 15
T5: 33
T6: 58
8. Assign 0 to left path and 1 to right path in the tree.
0
1
0
0
0
0
0 1
1
1
1
1
This tree is called Huffman tree.
70
Now the code for each characters are as obtained by collecting the bits from root
to the character node. The codes are:
Char code frequency
i 00 12
sp 01 13
e 10 15
nl 11000 1
S 11001 3
t 1101 4
a 111 10
Therefore, total number of bits required
= 12*2 +13 *2 + 15 *2 + 1 *5 +3 * 5 + 4*4 + 10 * 3
= 146 bits
The space saved = (174-146)/174 *100 %
= 16.09 %
71
AVL (Adelson-Velskii and Landis) Trees
• An AVL Tree is a
binary search tree
such that for every
internal node v of T,
the heights of the
children of v can differ
by at most 1.
88
44
17 78
32 50
48 62
2
4
1
1
2
3
1
1
An example of an AVL tree where the
heights are shown next to the nodes:
72
5
3 8
1 4 10
AVL Tree
5
3
1 4
Not AVL Tree
• All operations depend on the depth of the tree.
• BSTs are limited because of their bad worst-case performance O(n).
• AVL trees are height-balanced binary search trees
• An AVL tree has balance factor calculated at every node
For every node, heights of left and right subtree can differ by no more
than 1
• It allows dynamic insert and remove with O(log(N)) time complexity.
• Balanced search trees are trees whose heights in the worst case is
O(lg n)
73
Homework #7
1. Differentiate between preorder and inorder traversal.
2. Explain post order traversal.
3. What is binary tree? Explain their applications.
4. Explain Huffman's algorithm with example.
5. What is BST? Write the algorithm to search an element in
BST.
6. Explain the insertion of an element in BST.
7. Explain deletion of a node from BST.
75

More Related Content

PPTX
Unit – vi tree
PPTX
Mca iii dfs u-4 tree and graph
PDF
Lecture notes data structures tree
PPT
introduction to_trees
PPTX
Tree - Data Structure
PPT
358 33 powerpoint-slides_10-trees_chapter-10
PPTX
non linear data structure -introduction of tree
Unit – vi tree
Mca iii dfs u-4 tree and graph
Lecture notes data structures tree
introduction to_trees
Tree - Data Structure
358 33 powerpoint-slides_10-trees_chapter-10
non linear data structure -introduction of tree

What's hot (20)

PPTX
PPTX
Tree in data structure
PPSX
Data Structure (Tree)
PDF
Tree Data Structure by Daniyal Khan
PPTX
Types of Tree in Data Structure in C++
PPTX
Lecture 8 data structures and algorithms
PPT
Chapter 8 ds
PPTX
trees in data structure
PPTX
Tree in data structure
PPTX
Data structure tree - intermediate
PDF
Binary tree
PPT
Tree-In Data Structure
PPTX
Tree
PPTX
Data structure tree- advance
PPTX
Tree(Data Structure)
PPT
Trees - Non Linear Data Structure
PPTX
Search tree,Tree and binary tree and heap tree
PPTX
Data structure tree - beginner
PPT
Binary tree
Tree in data structure
Data Structure (Tree)
Tree Data Structure by Daniyal Khan
Types of Tree in Data Structure in C++
Lecture 8 data structures and algorithms
Chapter 8 ds
trees in data structure
Tree in data structure
Data structure tree - intermediate
Binary tree
Tree-In Data Structure
Tree
Data structure tree- advance
Tree(Data Structure)
Trees - Non Linear Data Structure
Search tree,Tree and binary tree and heap tree
Data structure tree - beginner
Binary tree
Ad

Similar to Unit 6 tree (20)

PPTX
Introduction to Tree_Data Structure.pptx
PPTX
binary tree.pptx
PPT
Lecture 5 tree.pptx
PDF
Chapter 5_Trees.pdf
PPTX
tree-160731205832.pptx
PPTX
Tree.pptx
PPT
Data Structure And Algorithms for Computer Science
PPTX
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
PPTX
BASIC TREE AND TYPES OF DI CONCEPTS.pptx
PPT
PPTX
UNIT III Non Linear Data Structures - Trees.pptx
PPTX
PPTX
tree Data Structures in python Traversals.pptx
PPTX
Unit-VStackStackStackStackStackStack.pptx
PPTX
Data structure using c module 2
PPT
ds 10-Binary Tree.ppt
PPTX
Introduction and basic of Trees and Binary Trees
PPTX
NON-LINEAR DATA STRUCTURE-TREES.pptx
PPTX
Basics of Binary Tree and Binary Search Tree.pptx
Introduction to Tree_Data Structure.pptx
binary tree.pptx
Lecture 5 tree.pptx
Chapter 5_Trees.pdf
tree-160731205832.pptx
Tree.pptx
Data Structure And Algorithms for Computer Science
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
BASIC TREE AND TYPES OF DI CONCEPTS.pptx
UNIT III Non Linear Data Structures - Trees.pptx
tree Data Structures in python Traversals.pptx
Unit-VStackStackStackStackStackStack.pptx
Data structure using c module 2
ds 10-Binary Tree.ppt
Introduction and basic of Trees and Binary Trees
NON-LINEAR DATA STRUCTURE-TREES.pptx
Basics of Binary Tree and Binary Search Tree.pptx
Ad

More from Dabbal Singh Mahara (20)

PPTX
Temporal databases
PPTX
Spatial databases
PPTX
Odbms concepts
PPTX
Object database standards, languages and design
PPTX
Normalization
PPTX
Mobile databases
PPTX
Active database
PPTX
Deductive databases
PPTX
Relational model
PPTX
Overview of dbms
PPTX
ER modeling
PPTX
EER modeling
PPTX
Unit 9 graph
PPTX
Unit 7 sorting
PPTX
Unit 5 linked list
PPTX
Unit 4 queue
PPTX
Unit 8 searching and hashing
PPTX
Unit 3 stack
PPTX
Unit 2 algorithm
Temporal databases
Spatial databases
Odbms concepts
Object database standards, languages and design
Normalization
Mobile databases
Active database
Deductive databases
Relational model
Overview of dbms
ER modeling
EER modeling
Unit 9 graph
Unit 7 sorting
Unit 5 linked list
Unit 4 queue
Unit 8 searching and hashing
Unit 3 stack
Unit 2 algorithm

Recently uploaded (20)

PPTX
web development for engineering and engineering
PDF
Structs to JSON How Go Powers REST APIs.pdf
PPTX
Internship_Presentation_Final engineering.pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
PPTX
24AI201_AI_Unit_4 (1).pptx Artificial intelligence
PDF
algorithms-16-00088-v2hghjjnjnhhhnnjhj.pdf
PPTX
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
Practice Questions on recent development part 1.pptx
PPTX
Road Safety tips for School Kids by a k maurya.pptx
PDF
Queuing formulas to evaluate throughputs and servers
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PDF
composite construction of structures.pdf
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
436813905-LNG-Process-Overview-Short.pptx
web development for engineering and engineering
Structs to JSON How Go Powers REST APIs.pdf
Internship_Presentation_Final engineering.pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
24AI201_AI_Unit_4 (1).pptx Artificial intelligence
algorithms-16-00088-v2hghjjnjnhhhnnjhj.pdf
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Practice Questions on recent development part 1.pptx
Road Safety tips for School Kids by a k maurya.pptx
Queuing formulas to evaluate throughputs and servers
Arduino robotics embedded978-1-4302-3184-4.pdf
composite construction of structures.pdf
Operating System & Kernel Study Guide-1 - converted.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS
436813905-LNG-Process-Overview-Short.pptx

Unit 6 tree

  • 2. Unit – 6 Tree Contents Hours Marks a. Concept and definition b. Binary tree c. Introduction and application d. Operations e. Types of binary tree  Complete binary tree  Strictly binary tree  Almost complete binary tree f. Tree traversal  Pre-order traversal  In-order traversal  Post-order traversal g. Binary search tree  searching  insertion  deletion h. Expression Tree i. Huffman algorithm j. AVL Trees 7 9 2
  • 3. Introduction • A tree is an abstract model of a hierarchical structure that consists of nodes with a parent-child relationship. • A tree is a finite set of data items or nodes such that:  There is a special data-item called the root of the tree  Its remaining data items are partitioned into mutually exclusive sub-sets, each of which itself is a tree, called sub-trees.
  • 4. Characteristics of trees  Non-linear data structure  Combines advantages of an ordered array  Searching as fast as in ordered array  Insertion and deletion as fast as in linked list 4
  • 5. Application  Directory structure of a file store  Structure of arithmetic expressions  Hierarchy of an organization 5
  • 6. Some Key Terms Degree of a node: • The degree of a node is the number of children of that node. In above tree , degree(A) = 2. Degree of a Tree: • The degree of a tree is the maximum degree of nodes in a given tree. In the above tree, maximum degree of nodes is 2, thus the degree of the tree is 2. Path: • It is the sequence of consecutive edges from source node to destination node. There is a single unique path from the root to any node. 6
  • 7. Some Key Terms  Height of a node: The height of a node is the maximum path length from that node to a leaf node. A leaf node has a height of 0.  Height of a tree: The height of a tree is the height of the root.  Depth of a node: Depth of a node is the path length from the root to that node. The root node has a depth of 0. 7
  • 8. Some Key Terms Level of a node: The level of a node is 0, if it is root; otherwise it is one more than its parent. Depth of a tree: Depth of a tree is the maximum level of any leaf in the tree. This is equal to the longest path from the root to any leaf. 8
  • 9. • A is the root node • B is the parent of E and F • D is the sibling of B and C • E and F are children of B • E, F, G, D are external nodes or leaves • A, B, C are internal nodes • Depth of F is 2 • the height of tree is 2 • the degree of node A is 3 • The degree of tree is 3 Illustration 9
  • 10. Binary Trees  A binary tree is 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 right sub-trees of the original tree. A left or right sub tree can be empty.  Each element of a binary tree is called a node of the tree. The following figure shows a binary tree with 9 nodes where A is the root. 10
  • 12. Properties of Binary Trees  If a binary tree contains m nodes at level l , it contains at most 2m nodes at level l + 1.  Since a binary tree can contain at most 1 node at level 0 (the root), it contains at most 2l nodes at level l. 12
  • 13. Types of Binary Trees • Strictly binary tree • Almost complete binary tree • Complete binary tree 13
  • 14.  If every non-leaf node in a binary tree has non-empty left and right sub-trees, then such a tree is called a strictly binary tree. Strictly binary tree  The following tree is not strictly binary tree, Since node E has a left son but not a right son. 14
  • 15.  A strictly binary tree of depth d is called complete binary tree if all of whose leaves are at level d.  A complete binary tree with depth d has 2d leaves and 2d -1 non-leaf nodes (internal). Complete binary tree: Example: In this tree d = 3, therefore, leaves = 23 = 8 Internal nodes = 23 -1 = 7 15
  • 16. A binary tree of depth d is an almost complete binary tree if: i. Any node at level less than d-1 has two sons. ii. For any node in the tree with a right descendant at level d, the node must have a left son and every left descendant of the node is either a leaf at level d or has two sons. Almost complete binary tree: 16
  • 17. B J G F C I ED H A K Level 0 Level 1 Level 2 Level 3 • This tree is not almost complete binary tree because it does not satisfy condition ii. • That is, node A has right descendent at level 3 ( J or K), but it has left descendent leaf node at level 2 (node E). 17
  • 18. Operations on Binary Tree • father(n,T): Return the parent node of the node n in tree T. If n is the root, NULL is returned. • LeftChild(n,T): Return the left child of node n in tree T. Return NULL if n does not have a left child. • RightChild(n,T): Return the right child of node n in tree T. Return NULL if n does not have a right child. • Info(n,T): Return information stored in node n of tree T (ie. Content of a node). • Sibling(n,T): return the sibling node of node n in tree T. Return NULL if n has no sibling. 18
  • 19. Operations on Binary Tree • Root(T): Return root node of a tree if and only if the tree is nonempty. • Size(T): Return the number of nodes in tree T • MakeEmpty(T): Create an empty tree T • SetLeft(S,T): Attach the tree S as the left sub-tree of tree T • SetRight(S,T): Attach the tree S as the right sub-tree of tree T. • Preorder(T): Traverses all the nodes of tree T in preorder. • postorder(T): Traverses all the nodes of tree T in postorder • Inorder(T): Traverses all the nodes of tree T in inorder. 19
  • 20. Binary Tree Representation • Array Representation – An array is used to store the nodes of the binary tree. – Nodes stored in the array are accessed sequentially, root is at index 0 and then left child and right child are stored. – To store the elements of the binary tree of depth d, declare the array of size 2d+1 -1, i.e. the total number of nodes of complete binary tree and store the elements level wise. – If root is at i then left child is t 2i+1 and right child is at 2i+2. 20
  • 21. B J G F C I ED H A0 1 2 4 7 5 14 6 3 10 • Declare array of size 2 3+1 -1 = 15 Char a[15] A B C D E F G H I J 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 21 Array Representation
  • 22. Linked Representation of Binary Tree • It is the most popular way to present a binary tree. Each element is represented by a node that has two link fields (leftChild and rightChild) plus an element field. Each binary tree node is represented as an object whose data type is binaryTreeNode . • The space required by an n node binary tree is: n * sizeof(binaryTreeNode) C representation for Binary tree struct binaryTreeNode { int info; struct binaryTreenode *left; struct binaryTreenode *right; }; struct binaryTreenode *root=NULL; 22
  • 23. The given tree can be represented in linked list as given below. 23
  • 24.  The tree traversal is a way in which each node in the tree is visited exactly once in a symmetric manner.  There are three popular methods of traversal i. Pre-order traversal ii. In-order traversal iii. Post-order traversal Tree traversal 24
  • 25. 1. Pre-order traversal: The preorder traversal of a nonempty binary tree is defined as follows: i. Visit the root node ii. Traverse the left sub-tree in preorder iii. Traverse the right sub-tree in preorder The preorder traversal output of the given tree is: A B D H I E C F G The preorder is also known as depth first order. C function for preorder traversing: void preorder(struct bnode *root) { if(root!=NULL) { printf(“%c”, root->info); preorder(root->left); preorder(root->right); } } 25
  • 26. The inorder traversal of a nonempty binary tree is defined as follows: i. Traverse the left sub-tree in inorder ii. Visit the root node iii. Traverse the right sub-tree in inorder The inorder traversal output of the given tree is: H D I B E A F C G C function for inorder traversing: void inorder(struct binaryTreenode *root) { if(root!=NULL) { inorder(root->left); printf(“%c”, root->info); inorder(root->right); } } 2. In-order traversal: 26
  • 27. 3. Post-order traversal: The post-order traversal of a nonempty binary tree is defined as follows: i. Traverse the left sub-tree in post-order ii. Traverse the right sub-tree in post-order iii. Visit the root node C function for post-order traversing: void post-order(struct bnode *root) { if(root!=NULL) { post-order(root->left); post-order(root->right); printf(“%c”, root->info); } } The post-order traversal output of the given tree is: H I D E B F G C A 27
  • 28. Q. Design a binary tree whose traversal sequences are given below: Pre-order: CPRBLOEMATIK In-Order: BRLPEOMCTAIK Solution: Since preorder traverses from root of the tree, C is root of the tree. The { B, R, L, P, E, O, M} and {T, I, A, K } are respectively left and right sub tree . (from inorder sequence) C T, A, I, K B, R, L, P, E, O, M 28
  • 29. C I, KB, R, L, P E, O, M A T • Similarly, for left sub tree { B, R, L, P, E, O, M}, root is P ( from preorder sequence) and {B, R, L} is left sub-tree and {E, O, M} is right sub-tree. ( From inorder sequence) • For right sub-tree {T, A, I, K}, A is the root. ( from preorder sequence) T is left sub-tree and {I, K } is right sub-tree. 29
  • 30. • Similarly, R is root for sub-tree {B, R, L} ( from preorder sequence) B is left child and L right child of R ( from inorder sequence) • O is root for sub-tree {E, O, M} (from preorder sequence) E is left child and M is right child of O (from inorder sequence) • In the same way, I is root and K is right child for sub-tree { I, K } C P A TO I KL M R EB 30
  • 31. Q. A binary tree T has 12 nodes. The in-order and post-order traversals of T yield the following sequence of nodes: In-order : VPNAQRSOKBTM Post-order : VANRQPBKOMTS Construct the Binary tree T showing each step. Explain how you can arrive at solution in brief. Solution: Since post-order traversal visits all nodes in left sub-tree , right sub-tree and root recursively, the last node in the sequence is root of the tree. That is, S is the root. In-order traversal visits the nodes in Left child, root and right child in recursive way, { V,P, N,A, Q, R} is left sub-tree and {O, K, B, T, M} is the right sub tree. S O, K, B, T, M V, P, N, A, Q, R Step -1: 31
  • 32. • Step -2: The root of { V, P, N, A, Q, R} is P obtained from postorder sequence. Left subtree and right sub trees are {v} and {N, A, Q, R} obtained from inorder sequence. • Similarly, for { O, K, T, B, M} , root is T and left sub tree {O, K, B} and right sub tree is {M}. 32 S O, K, B P T MV N, A, Q, R
  • 33. O S K, B P N, A T MV Q R Step -3: In the same way, root and sub trees are obtained. 33
  • 34. S P T MV Q R Step -4: The final tree is given below. O K B A N • Thus, root of the tree is obtained from post-order sequence scanning from right to left and left and right sub-trees of corresponding root are obtained from inorder sequence. 34
  • 35. • An important application of binary trees is their use in searching. • A binary search tree (BST) is a binary tree that is either empty or in which every node contains a key (value) and satisfies the following conditions: i. All keys in the left sub-tree of the root are smaller than the key in the root node. ii. All keys in the right sub-tree of the root are greater than the key in the root node. iii. The left and right sub-trees of the root are again binary search trees . Binary search tree(BST) 35
  • 36. Binary Search Trees 1 4 2 3 8 6 1 4 2 3 8 6 7 • The tree on the left is a binary search tree, but the tree on the right is not. 36
  • 37. • Given the following sequence of numbers, 14, 15, 4, 9, 7, 18, 3, 5, 16, 20, 17, 5 • The following binary search tree can be constructed: 14 4 9 15 7 5 17 2016 3 18 • The inorder traversal of BST gives the sorted sequence in ascending order. So, inorder traversal of above BST is: 3, 4, 5, 7, 9, 14, 15, 16, 17, 18, 20. 37
  • 38. Following operations can be done in BST:  Search(k, T): Search for key k in the tree T. If k is found in some node of tree then return true otherwise return false.  Insert(k, T): Insert a new node with value k in the info field in the tree T such that the property of BST is maintained.  Delete(k, T):Delete a node with value k in the info field from the tree T such that the property of BST is maintained.  FindMin(T), FindMax(T): Find minimum and maximum element from the given nonempty BST. Operations on Binary search tree(BST): 38
  • 39. struct bstnode { int info; //Declaring an info field struct bstnode *left; // left child pointer struct bstnode *right; // right child pointer }; Structure of BST node Struct bstnode *root = NULL; 39
  • 40. To find if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: 2.1. If curr is null: 2.1.1. Terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element: 2.2.1. Terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element: 2.3.1. Set curr to curr’s left child. 2.4. Otherwise, if target is greater than curr’s element: 2.4.1. Set curr to curr’s right child. 3. end BST search algorithm : 40
  • 41. C function for BST searching: void BinSearch(struct bstnode *root , int key) { if(root == NULL) { printf(“The number does not exist”); } else if (key == root->info) { printf(“The searched item is found”): } else if(key < root->info) BinSearch(root->left, key); else BinSearch(root->right, key); } 41
  • 42. • To insert a new item in a tree, we must first verify that its key is different from those of existing elements. To do this a search is carried out. If the search is unsuccessful, then item is inserted. • Idea: To insert a new element into a BST, proceed as if searching for that element. If the element is not already present, the search will lead to a null link. Replace that null link by a link to a leaf node containing the new element. Insertion of a node in BST: 15 9 13 12 10 18 20 22 25 Insertion of element 13 42
  • 43. To insert the element elem into a BST: 1. Set parent to null, and set curr to the BST’s root. 2. Repeat: 2.1. If curr is null: 2.1.1. Replace the null link from which curr was taken (either the BST’s root or parent’s left child or parent’s right child) link to a newly-created leaf node with element elem. 2.1.2. Terminate. 2.2. Otherwise, if elem is equal to curr’s element: 2.2.1. Terminate. 2.3. Otherwise, if elem is less than curr’s element: 2.3.1. Set parent to curr, and set curr to curr’s left child. 2.4. Otherwise, if elem is greater than curr’s element: 2.4.1. Set parent to curr, and set curr to curr’s right child. 3.End BST insertion algorithm : 43
  • 44. C function for BST insertion: Struct bstnode * insert(struct bstnode *root, int item) { if(root=NULL) { root=(struct bstnode*)malloc (sizeof(struct bnode)); root->left = root->right=NULL; root->info = item; } else if ( item == root->info) { printf("n Duplicate not allowed."); return root; } else { if(item<root->info) root->left=insert(root->left, item); else root->right=insert(root->right, item); } } 44
  • 45. While deleting a node from BST, there may be three cases: 1. The node to be deleted may be a leaf node: In this case simply delete a node and set null pointer to its parents those side at which this deleted node exist. Deleting a node from the BST: 45
  • 46. 2. The node to be deleted has one child: In this case the child of the node to be deleted is appended to its parent node. Suppose node to be deleted is 18 Delete(18) 46
  • 47. 3. The node to be deleted has two children: In this case node to be deleted is replaced by its in-order successor node. That is, the node to be deleted is either replaced by its right sub-trees leftmost node or its left sub-trees rightmost node. Suppose node to deleted is 12. Find minimum element in the right sub- tree of the node to be removed. In current example it is 19. Delete(12) 47
  • 48. 1. start 2. if a node to be deleted is a leaf node at left side then simply delete and set null pointer to it's parent's left pointer. 3. If a node to be deleted is a leaf node at right side then simply delete and set null pointer to it's parent's right pointer. 4. if a node to be deleted has one child then connect it's child pointer with it's parent pointer and delete it from the tree. 5. if a node to be deleted has two children then replace the node being deleted either by a. right most node of it's left sub-tree or b. left most node of it's right sub-tree. 6. End 48 General algorithm to delete a node from a BST
  • 49. Delete a node in BST struct bstnode *delnode(struct bstnode *root, int item) { struct bstnode *temp; if(root==NULL) { printf(“Empty tree”); return; } else if(item<root->info) root->left=delnode(root->left, item); else if(item>root->info) root->right=delnode(root->right, item); else if(root->left!=NULL && root->right!=NULL) //node has two children { temp=findmin(root->right); root->info=temp->info; root->right=delnode(root->right, root->info); } else { temp=root; if(root->left==NULL) root=root->right; else if(root->right==NULL) root=root->left; free(temp); } return(root); } 49
  • 50. struct bstnode * findmin(struct bstnode * root) { if(root==NULL) return NULL; else if(root->left ==NULL) return head; else return(findmin(root->left)); } Findmin Function 50
  • 51. Expression Tree • An expression tree is a strictly binary tree in which leaf node contains operands and non-leaf node contain operators. • Root nodes contain the operators that is applied to the result of left and right sub trees. • The operators, constants, and variables are arranged in such a way that an inorder traversal of the tree produces the original expression without parentheses. • Example: An expression tree of an expression (a + b *c ) +((c*e +f) *g) *a + * g+ f * ec c + b 51
  • 52. Exercise • Construct an expression tree of an expression: (a + b ) /((c-d) *e) 52
  • 53. Expression Tree Examples Inorder Traversal ResultExpression TreeExpression a + 3(a+3) 3+4*5-9+63+(4*5-(9+6)) log xlog(x) n !n! + 3a + -3 * 54 + 69 log x ! n 53
  • 54. Constructing an Expression Tree From Postfix Expression Algorithm 1. Read the expression one symbol at a time. 2. If the symbol is an operand, we create a one-node tree and push a pointer to it onto a stack. 3. If the symbol is an operator, we pop pointers to two trees T1 and T2 from the stack (T1 is popped first) and form a new tree whose root is the operator and whose left and right children point to T2 and T1, respectively. A pointer to this new tree is then pushed onto the stack. 54
  • 55. • Input: ab+cde+**  The first two symbols are operands, so we create one-node trees and push pointers to them onto a stack. For convenience, we will have the stack grow from left to right in the diagrams. 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 a one- node tree is created and a pointer to the corresponding tree is pushed onto the stack. a b + c d e 55 Example: Constructing an Expression Tree
  • 56. Constructing an Expression Tree a b + c • Now a ‘+’ is read, so two trees are merged. d e + a b + c  Continuing, a ‘*’ is read, so we pop two tree pointers and form a new tree with a ‘*’ as root. d e + * 56
  • 57. Constructing an Expression Tree a b + c  Finally, the last symbol is read, two trees are merged, and a pointer to the final tree is left on the stack. d e + * * Exercise: Construct an expression from postfix expression: AB+C*DC--FG+$ 57
  • 58. • Proposed by Dr. David A. Huffman at MIT in 1952 – “A Method for the Construction of Minimum Redundancy Codes” • Huffman coding is a form of statistical coding – more frequently used symbols have shorter code words – Not all characters occur with the same frequency! – Yet all characters are allocated the same amount of space – 1 char = 1 byte, be it e or x • Huffman coding is a technique used to compress files for transmission • Works well for text and fax transmissions The Huffman Coding 58
  • 59. • Huffman codes is text compression method, which relies on the relative frequency (i.e., the number of occurrences of a symbol) with which different symbols appear in a text • Uses extended binary trees • Variable-length codes that satisfy the property, where no code is a prefix of another • Huffman tree is a binary tree with minimum weighted external path length for a given set of frequencies (weights). 59 Huffman Code
  • 60. Huffman Algorithm 1.Initially, each symbol is one node tree by itself. That is, there is forest of n nodes each labelled with symbol and weight. 2.Repeat while n>1 i. Select the two trees T1 and T2 with minimum weights from the forest. ii. Merge T1 and T2 to form T3 with weight sum of both trees. iii. Insert T3 into the forest. 3. Assign 0 to each left path of tree and 1 to right path. The code for each symbol is obtained by collecting bits on the paths from root to the leaf node labelled with the symbol. 60
  • 61. Example: 1 Let us take any four characters and their frequencies as follows: Char frequency E 10 T 7 O 5 A 3 • Without using Huffman coding, these four characters can be represented by using two bits as: 00 -> E, T ->01, O ->10 and A-> 11. This is fixed length coding. So, bits required to encode all the characters in the above message will be: ( 10 +7+5+3) * 2 = 50 bits • Huffman coding technique uses variable length code depending upon the frequency of characters used in the text. It's coding technique is as follows: First sort the characters by their frequency in non-decreasing order. Char frequency A 3 O 5 T 7 E 10 61
  • 62. 1. Create a forest of one node trees for each character as: A : 3 O : 5 T : 7 E: 10 2. Merge two minimum trees as a single tree and add it to the forest in the order. T1 : 8 O: 5A : 3 T : 7 E: 10 3. Repeat step 2 again. T2 : 15 T : 7 T1 : 8 O: 5A : 3 E: 10 62
  • 63. 4. Repeat the step 2 again. T3: 25 E: 10 T2 : 15 T : 7 T1 : 8 O: 5A : 3 T3: 25 E: 10 T2 : 15 T : 7 T1 : 8 O: 5A : 3 5. Assign 0 to left path and 1 to right path in the tree. 0 0 0 1 1 1 This tree is called Huffman tree. 63
  • 64. Now the code for each characters are as obtained by collecting the bits from root to the character node. The codes are: Char code frequency E 0 10 T 10 7 A 110 3 O 111 5 Therefore, total number of bits required = 10* 1 +7 *2 + 3 *3 + 5 *3 =48 bits The space saved = (50-48)/50 *100 % = 4 % 64 Huffman Code
  • 65. Example: 2 Let us take any four characters and their frequencies as follows: Char frequency a 10 e 15 i 12 s 3 t 4 Sp (space) 13 nl (new line) 1 Fixed Length Format: These 7 characters can be represented by three bits. So, total number of bits = (10+15+12+3+4+13+1) * 3 = 174 Using Huffman Coding First sort the characters by their frequency in non-decreasing order. Char frequency nl (new line) 1 s 3 t 4 a 10 i 12 Sp (space) 13 e 15 65
  • 66. 1. Create a forest of one node trees for each character as: 2. Merge two minimum trees as a single tree and add it to the forest in the order. T1 : 4 S : 3 nl : 1 3. Repeat step 2 again. nl : 1 s: 3 t : 4 a: 10 i: 12 sp: 13 e: 15 t : 4 a: 10 i: 12 sp: 13 e: 15 a: 10 i: 12 sp: 13 e: 15 T2 : 8 T1 : 4 S : 3 nl : 1 t : 4 66
  • 67. 4. Repeat step 2 again. i: 12 sp: 13 e: 15 T2 : 8 T1 : 4 S : 3nl : 1 t : 4 T3 : 18 a : 10 5. Repeat step 2 again. e: 15 T4: 25 sp: 13i: 12 T2 : 8 T1 : 4 S : 3nl : 1 t : 4 T3 : 18 a : 10 67
  • 68. 6. Repeat step 2 again. sp: 13 T4: 25 i: 12 T2 : 8 T1 : 4 S : 3nl : 1 t : 4 T3 : 18 a : 10 e: 15 T5: 33 68
  • 69. sp: 13 T4: 25 i: 12 T2 : 8 T1 : 4 S : 3nl : 1 t : 4 T3 : 18 a : 10 e: 15 T5: 33 T6: 58 7. Repeat step 2 again. 69
  • 70. sp: 13 T4: 25 i: 12 T2 : 8 T1 : 4 S : 3nl : 1 t : 4 T3 : 18 a : 10 e: 15 T5: 33 T6: 58 8. Assign 0 to left path and 1 to right path in the tree. 0 1 0 0 0 0 0 1 1 1 1 1 This tree is called Huffman tree. 70
  • 71. Now the code for each characters are as obtained by collecting the bits from root to the character node. The codes are: Char code frequency i 00 12 sp 01 13 e 10 15 nl 11000 1 S 11001 3 t 1101 4 a 111 10 Therefore, total number of bits required = 12*2 +13 *2 + 15 *2 + 1 *5 +3 * 5 + 4*4 + 10 * 3 = 146 bits The space saved = (174-146)/174 *100 % = 16.09 % 71
  • 72. AVL (Adelson-Velskii and Landis) Trees • An AVL Tree is a binary search tree such that for every internal node v of T, the heights of the children of v can differ by at most 1. 88 44 17 78 32 50 48 62 2 4 1 1 2 3 1 1 An example of an AVL tree where the heights are shown next to the nodes: 72
  • 73. 5 3 8 1 4 10 AVL Tree 5 3 1 4 Not AVL Tree • All operations depend on the depth of the tree. • BSTs are limited because of their bad worst-case performance O(n). • AVL trees are height-balanced binary search trees • An AVL tree has balance factor calculated at every node For every node, heights of left and right subtree can differ by no more than 1 • It allows dynamic insert and remove with O(log(N)) time complexity. • Balanced search trees are trees whose heights in the worst case is O(lg n) 73
  • 74. Homework #7 1. Differentiate between preorder and inorder traversal. 2. Explain post order traversal. 3. What is binary tree? Explain their applications. 4. Explain Huffman's algorithm with example. 5. What is BST? Write the algorithm to search an element in BST. 6. Explain the insertion of an element in BST. 7. Explain deletion of a node from BST.
  • 75. 75