0% found this document useful (0 votes)
4 views

DSA.unit4

The document outlines the curriculum for the SY B.Tech 2023 Scheme focusing on Trees and Search Trees as part of the Department of Information Technology. It covers various topics including tree definitions, properties, types of binary trees, operations on binary trees, and traversal algorithms. The goal is to implement nonlinear data structures to efficiently manage hierarchical and relational datasets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

DSA.unit4

The document outlines the curriculum for the SY B.Tech 2023 Scheme focusing on Trees and Search Trees as part of the Department of Information Technology. It covers various topics including tree definitions, properties, types of binary trees, operations on binary trees, and traversal algorithms. The goal is to implement nonlinear data structures to efficiently manage hierarchical and relational datasets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 145

Department of Information Technology

SY. B.Tech 2023 Scheme (As per NEP 2020)

Semester- III

1
UNIT 4.

TREES AND SEARCH TREES

Mapping of Course Outcomes- CO4


CO4: IMPLEMENT NONLINEAR DATA STRUCTURES TO MANAGE AND
MANIPULATE EFFICIENTLY THE HIERARCHICAL, RELATIONAL DATASETS.

Prepared by Prof. Yogesh Gite


Topics
3

◻ Trees - Basic terminology, General tree, Representation


◻ Binary tree
properties
converting tree to binary tree
Operations on Binary tree
Tree Traversal Algorithms : Preorder, Inorder, Postorder Traversal
◻ Search Trees: Binary Search Trees (BST)
BST Operations
◻ Threaded BST (TBST)-
Thread concept & operations on TBST
◻ Huffman Encoding.
◻ Height Balanced Tree-
AVL Trees & operations on AVL tree,
◻ m-way Search Trees,
B-Tree,
B+ Tree.
Introduction
4

◻ Data structure such as Arrays, Stacks, Linked List and Queues


are linear data structure. Elements are arranged in linear
manner i.e. one after another.
◻ Tree is a non-linear data structure.
◻ Tree imposes a Hierarchical structure, on a collection
of items.
◻ Several Practical applications
Organization charts.
Family hierarchy
Representation of algebraic expression
Introduction
Organizational Chart
5
Introduction
6

◻ Representation of algebraic expression


Z=(J - K) / ((L * M) + N)
Tree Definition
7

◻ A tree is a collection of nodes


The collection can be empty
If not empty, a tree consists of a distinguished node R (the
root), and zero or more nonempty subtrees T1, T2, ...., Tk,
each of whose roots are connected by a directed edge from
R.
Tree Definition
8
Tree Terminologies
9

◻ Root
It is the mother node of a tree structure. This tree does not
have parent. It is the first node in hierarchical arrangement.
◻ Node
The node of a tree stores the data and its role is the same as
in the linked list. Nodes are connected by the means of links
with other nodes.
◻ Parent
It is the immediate predecessor of a node. In the figure A is
the parent of B and C. A

B C
A

Tree Terminologies
B C
10

◻ Child
When a predecessor of a node is parent then all successor
nodes are called child nodes. In the figure B and C are the
child nodes of A
◻ Link / Edge
An edge connects the two nodes. The line drawn from one
node to other node is called edge / link. Link is nothing but a
pointer to node in a tree structure.
◻ Leaf
This node is located at the end of the tree. It does not have
any child hence it is called leaf node.
Tree Terminologies
11

◻ Level
Level is the rank of tree hierarchy. The whole tree structured is leveled.
The level of the root node is always at 0. the immediate children of root
are at level 1 and their children are at level 2 and so no.
◻ Height
The highest number of nodes that is possible in a way starting from the
first node (ROOT) to a leaf node is called the height of tree. The formula
for finding the height of a tree , where h is the height and I
is the max level of the tree
Root node

Interior nodes Height

Leaf nodes
Tree Terminologies
12

◻ Sibling
The child node of same parent are called sibling. They are also called
brother nodes.
◻ Degree of a Node
The maximum number of children that exists for a node is called as
degree of a node.
◻ Terminal Node
The node with out degree zero is called terminal node or leaf.
◻ Path length.
Is the number of successive edges from source node to destination
node.
◻ Ancestor and descendant
Proper ancestor and proper descendant
Tree Terminologies
13

◻ Depth
Depth of a binary tree is the maximum level of any leaf of a tree.
◻ Forest
It is a group of disjoint trees. If we remove a root node from a tree then
it becomes the forest.
In the following example, if we remove a root A then two disjoint
sub-trees will be observed. They are left sub-tree B and right sub-tree C.
A

B C

D E F
Notation
14

node
A
•root
•left subtree B C
•right subtree

D E F

G H I

It consists of a root and two subtrees


Notation
15

B C

D E F

G H I
edge –
there is an edge from the root to its children
Notation
16

children
B C

D E F

G H I
Notation
17

children
Who are node C’s children?
A

Who are node A’s children?


B C

D E F

G H I
Notation
18

descendants
B C

Who are node C’s descendants? D E F

G H I

Who are node A’s descendants?


Notation
19

parents A

B C

D E F
Who is node E’s parent?

Who is node H’s parent? G H I


Notation
20

ancestors
B C

D E F
Who are node D’s ancestors?

Who are node H’s ancestors? G H I


Notation
21

from J to A
A

path – B C

If n1, n2,…nk is a sequence D E F


of nodes such that ni is the
parent of ni+1, then that
sequence is a path.
G H I
■The length of the path is k-1.

J
Notation
22

B C

2 D E F

depth –
the length of the path
G H I
from the root of the tree
to the node
Notation
23

0 A

1 B C

2 D E F

3 G H I
level –
all nodes of depth d are at level d in the tree
Notation
24

B C

D E F

G H I
leaf node –
any node that has two empty children
Notation
25

B C

D E F

G H I
internal node –
any node that has at least one non-empty Child
Or
An internal node of a tree is any node which has degree greater than one.
Binary Trees
26

◻ The simplest form of tree is a binary tree. A binary tree


consists of
a node (called the root node) and
left and right sub-trees.
Both the sub-trees are themselves binary trees

◻ We have a recursively defined data structure.

◻ Also, a tree is binary if each node of it has a maximum of two


branches i.e. a node of a binary tree can have maximum two
children. 0 1 2
Binary Tree
27
Binary Tree
28
Binary Trees
29

Some Binary Trees


One node Two nodes

Three nodes
Degenerate (or pathological) tree
30

◻ A Tree where every internal node has one child. Such trees are
performance-wise same as linked list.
◻ It is a tree having a single child either left or right.
Skewed Binary tree
31

◻ It is a pathological/degenerate tree in which the tree is either


dominated by the left nodes or the right nodes.
◻ There are two types of skewed binary tree: left-skewed binary
tree and right-skewed binary tree.
Types- On basis of the completion of levels
32
Strictly Binary Tree
◻ When every non-leaf node in binary tree is filled with left and
right sub-trees, the tree is called strictly binary tree.

B C

D E

F G
Types- On basis of the completion of levels
33
Complete Binary Tree
A Complete binary tree is:
▪ A tree in which each level of the tree is completely filled.

Except, possibly the bottom level.


A

B C

D E F G

H I J
Types- On basis of the completion of levels
34
Balanced Binary Tree
❑ A binary tree is balanced if the height of the tree is O(Log n) where n is the
number of nodes.
❑ For Example, the AVL tree, Red-Black trees
Static Implementation of Binary Tree
35
- Sequential Representation
(1) waste space [1] A
A [1] A (2) insertion/deletion [2] B
[2] B problem [3] C
[3] --
B A [4] D
[4] C
-- [5] E
[5] [6] F
C --
[6] [7] G
-- B C
[7] D [8] H
D [8] [9] I
[9] -- F G
D E
. .
E E
[16
] H I
Dynamic Implementation of Binary Tree
36
- Linked Implementation
typedef struct node *tree_pointer;
typedef struct node {
int data;
tree_pointer left_child, right_child;
};
dat
a
left_child dat right_child
a
left_child right_child
Dynamic Implementation of Binary Tree
37
- Linked Implementation
Dynamic Implementation of Binary Tree
38
- Linked Implementation
Dynamic Implementation of Binary Tree
- Linked Implementation Structure Definition
39

◻ The fundamental component of binary tree is node.


◻ In binary tree node should consist of three things.
Data
■ Stores given values
Left child
■ is a link field and hold the address of its left node
Right child.
■ Is a link field and holds the address of its right node.
struct node
{
int data
node *left_child;
node *right_child;
};
Operations on Binary Tree
40

◻ Create
Create an empty binary tree
◻ Empty
Return true when binary tree is empty else return false.
◻ Lchild
A pointer is returned to left child of a node, when a node is without
left child, NULL pointer is returned.
◻ Rchild
A pointer is returned to right child of a node, when a node is without
right child, NULL pointer is returned.
◻ Father/Parent
A pointer to father of a node is returned.
Operations on Binary Tree
41

◻ Sibling
A pointer to brother of the node is returned or else NULL pointer is returned.
◻ Tree Traversal
Inorder Traversal infix A+B
Preorder Traversal prefix +AB
Postorder Traversal postfix AB+
◻ Insert
To insert a node
◻ Deletion
To delete a node
◻ Search
To search a given node
◻ Copy
Copy one tree into another.
Traversal of a Binary Tree
42

◻ Used to display/access the data in a tree in a certain order.


◻ In traversing always right sub-tree is traversed after left
sub-tree.
◻ Three methods of traversing
Preorder Traversing
■ Root – Left –Right
Inorder Traversing
■ Left – Root – Right
Postorder Traversing
■ Left – Right - Root
Traversal of a Binary Tree
43

◻ Used to display/access the data in a tree in a certain order.


◻ In traversing always right sub-tree is traversed after left
sub-tree.
◻ Three methods of traversing
Preorder Traversing
■ Root – Left –Right
Inorder Traversing
■ Left – Root – Right
Postorder Traversing
■ Left – Right - Root
Traversal of a Binary Tree
44
Example: Expression Trees
45
◻ Leaves are operands (constants or variables)

◻ The other nodes (internal nodes) contain operators


Inorder Traversal
46

◻ Inorder traversal
left, node, right.
infix expression
■ a+b*c+d*e+f*g
Inorder Traversal
47

◻ Inorder traversal
left, node, right.
infix expression
■ a+b*c+d*e+f*g
Inorder Traversal Function
48

void BinaryTree::InorderTraversal(node* temp)


{
if(temp!=NULL)
{
InorderTraversal(temp->LTree);
cout<< temp->data;
InorderTraversal(temp->RTree);
}
}
Preorder Traversal
49

◻ Preorder traversal
RootNode – Left – Right
Prefix expression
■ ++a*bc*+*defg
Preorder Traversal Function
50

void BinaryTree::PreorderTraversal(node* temp)


{
if(temp!=NULL)
{
cout<<temp->data;
PreorderTraversal(temp->LTree);
PreorderTraversal(temp->RTree);
}
}
Postorder Traversal
51

◻ Postorder Traversal
left, right, node
postfix expression
■ abc*+de*f+g*+
Postorder Traversal Function
52

void BinaryTree::PostorderTraversal(node* temp)


{
if(temp!=NULL)
{
PostorderTraversal(temp->LTree);
PostorderTraversal(temp->RTree);
cout<< temp->data;
}
}
Inorder Traversal (recursive version)
53

void inorder(tree_pointer ptr)


/* inorder tree traversal */
{
A/B*C*D+E
if (ptr) {
inorder(ptr->left_child);
printf(“%d”, ptr->data);
indorder(ptr->right_child);
}
}
Preorder Traversal (recursive version)
54

void preorder(tree_pointer ptr)


/* preorder tree traversal */
{
+**/ABCDE
if (ptr) {
printf(“%d”, ptr->data);
preorder(ptr->left_child);
predorder(ptr->right_child);
}
}
Postorder Traversal (recursive version)
55

void postorder(tree_pointer ptr)


/* postorder tree traversal */
{
AB/C*D*E+
if (ptr) {
postorder(ptr->left_child);
postdorder(ptr->right_child);
printf(“%d”, ptr->data);
}
}
CHAPTER 5
Traversal Exercise
56

Traverse the following tree.

Pre-order Traversal?
Post-order Traversal?
In-order Traversal?
Traversal Exercise
57

Traverse the following tree.

Pre-order Traversal?
Post-order Traversal?
In-order Traversal?
Converting General Tree to Binary Tree
58

Example 1 dat
left childa right sibling
Converting General Tree to Binary Tree
59
Converting General Tree to Binary Tree
60

Example 2
Converting General Tree to Binary Tree
61

Example 3
Converting General Tree to Binary Tree
62

Example 3
Special Types of Trees
63

Binary Tree is classified On the basis of node values into the


following special types:
◻ Binary Search Tree
◻ AVL Tree
◻ B Tree
◻ B+ Tree
◻ Red Black Tree
◻ Segment Tree
Binary Search Tree
64

◻ Stores keys in the nodes in a way so that searching,


insertion and deletion can be done efficiently.
◻ Binary search tree is either empty or each node N of tree
satisfies the following property
The Key value in the left child is not more than the value of
root
The key value in the right child is more than or identical to the
value of root
All the sub-trees, i.e. left and right sub-trees follow the two
rules mention above.
Binary Search Tree
65

5
2 7

10 2

1
5 ,6 7,8
2, 3, 4
Examples
66

A binary search tree Not a binary search tree


Example 2
67

Two binary search trees representing the same Data set:


Example 3
68
Example
Input list of numbers:
69

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4
Example
Input list of numbers:
70

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
5
Example
Input list of numbers:
71

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5
Example
Input list of numbers:
72

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

9
Example
Input list of numbers:
73

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

7
Example
Input list of numbers:
74

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

1
9
8

7
Example
Input list of numbers:
75

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

1
3 9
8

7
Example
Input list of numbers:
76

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

1
3 9
8

5
Example
Input list of numbers:
77

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

1
3 9
8

1
7 6

5
Example
Input list of numbers:
78

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

1
3 9
8

1
7 6

4
Example
Input list of numbers:
79

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

1
3 9
8

1 2
7 6 0

4
Example
Input list of numbers:
80

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

1
3 9
8

1 2
7 6 0

1
5 7

4
Example
Input list of numbers:
81

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

1
3 9
8

1 2
7 9 6 0

1
5 7

4
Example
Input list of numbers:
82

14 15 4 9 7 18 3 5 16 4 20 17 9 14 5
1
4

1
4
5

1 1
3 9
4 8

1 2
7 9 6 0

1
5 7

4
Example
Input list of numbers:
83

14 15 4 9 7 18 3 5 16 4 20 17 9 14
1
5
4

1
4
5

1 1
3 9
4 8

1 2
7 9 6 0

1
5 7

4 5 “Binary Search Tree” of a given data


set
Binary Tree Implementation
84

Class BinaryTree{
private:
struct node{
int data;
node* LTree;
node* RTree;
};
public:
node* root;
BinaryTree( ){ root = NULL; }
node* Insert(node* , int);
void Search(node* , int);
void InorderTraversal(node*);
void PreorderTraversal(node*);
void PostorderTraversal(node*);
};
Binary Search Tree
85

◻ It is a data structure used for organizing and storing data in a


sorted manner.
◻ Each node in a Binary Search Tree has at most two children,
a left child and a right child, with the left child containing
values less than the parent node and the right child containing
values greater than the parent node.
◻ This hierarchical structure allows for
efficient searching, insertion, and deletion operations on the
data stored in the tree.
Searching in Binary Search Tree
86

◻ Three steps of searching


The item which is to be searched is compared with the root node. If
the item is equal to the root, then we are done.
If its less than the root node then we search in the left sub-tree.
If its more than the root node then we search in the right sub-tree.

◻ The above process will continue till the item is found or you
reached end of the tree.
Searching in Binary Search Tree
87
Search Function
88

void BinaryTree::Search(node* temp, int num)


{
if(temp==NULL)
cout<<“Number not found";
else if(temp->data == num)
cout<<"Number found";
else if(temp->data > num)
Search(temp->LTree, num);
else if(temp->data < num)
Search(temp->RTree, num);
}
Insertion in BST
89

◻ Three steps of insertion


If the root of the tree is NULL then insert the first node and root points
to that node.
If the inserted number is lesser than the root node then insert the
node in the left sub-tree.
If the inserted number is greater than the root node then insert the
node in the right sub-tree.
Insertion Function
90
node* BinaryTree::Insert(node* temp, int num)
{
if ( temp == NULL )
{
temp = new node;
temp->data= num;
temp->LTree= NULL;
temp->RTree=NULL;
}
else if(num < temp->data)
temp->LTree = Insert(temp->LTree, num);
else if( num >= temp->data)
temp->RTree = Insert(temp->RTree,num);
return temp;
}
Deletion in BST
91

◻ When we delete a node, we need to consider how


we take care of the children of the deleted node.
This has to be done such that the property of the search
tree is maintained.
Deletion in BST
92

Three cases:
(1) The node is a leaf
Delete it immediately
(2) The node has one child
Adjust a pointer from the parent to bypass that node
Deletion in BST
93

(3) The node has 2 children


Replace the key of that node with the minimum element at the
right subtree
Delete the minimum element
■ Has either no child or only right child because if it has a left child, that
left child would be smaller and would have been chosen. So invoke
case 1 or 2.
Deletion in BST
94

void BTree::DeleteNode(node* temp, int num)


{ if (temp==NULL)
cout<<"Number not Found";
else if((temp->data == num))
{ node *parent, *min ;
int number;
// if number is found at a leaf node
if((temp->LTree == NULL) && (temp->RTree == NULL))
{
parent=GetParent(root, temp->data, root); //will return parent node
if(parent->LTree == temp)
parent->LTree = NULL;
else if (parent->RTree == temp)
parent->RTree = NULL;
delete temp;
}
// if node to be deleted has one child
else if(((temp->LTree == NULL) && (temp->RTree != NULL)) || ((temp->LTree
!= NULL) && (temp->RTree == NULL)))
95 {
parent = GetParent(root, temp->data, root); //will return parent node
if(temp->LTree != NULL){
if(parent->LTree == temp)
parent->LTree = temp->LTree;
else if (parent->RTree == temp)
parent->RTree = temp->LTree;
}
else if(temp->RTree != NULL){
if(parent->LTree == temp)
parent->LTree = temp->RTree;
else if (parent->RTree == temp)
parent->RTree = temp->RTree;
}
delete temp;
}
96

//if node to be deleted has two children


else if((temp->LTree != NULL) && (temp->RTree != NULL))
{
min = FindMin(temp->RTree); //will return the min. no. found in RTree
number = min->data;
DeleteNode(temp->RTree, min->data); //calling to itself recursively
temp->data= number;
}
}

else if (num < temp->data)


DeleteNode(temp->LTree, num); //calling to itself recursively
else if (num > temp->data)
DeleteNode(temp->RTree, num); //calling to itself recursively
}
Topics
97

◻ Trees - Basic terminology, General tree, Representation


◻ Binary tree
properties
converting tree to binary tree
Operations on Binary tree
Tree Traversal Algorithms : Preorder, Inorder, Postorder Traversal
◻ Search Trees: Binary Search Trees (BST)
BST Operations
◻ Threaded BST (TBST)-
Thread concept & operations on TBST
◻ Huffman Encoding.
◻ Height Balanced Tree-
AVL Trees & operations on AVL tree,
◻ m-way Search Trees,
B-Tree,
B+ Tree.
Threaded BST (TBST) – Why
98

◻ Inorder traversal of a Binary tree can either be done using recursion or with
the use of a auxiliary stack.
◻ The idea of TBST is to make inorder traversal faster and do it without stack
and without recursion.
◻ A binary tree is made threaded by making all right child pointers that would
normally be NULL point to the inorder successor of the node (if it exists).
◻ A TBST is a type of binary tree data structure where the empty left and right
child pointers in a binary tree are replaced with threads that link nodes
directly to their in-order predecessor or successor, thereby providing a way to
traverse the tree without using recursion or a stack.
◻ TBST can be useful when space is a concern, as they can eliminate the need
for a stack during traversal.
◻ TBST can be more complex to implement than standard binary trees.
Threaded BST (TBST)
99
Threaded BST (TBST)
100

◻ Binary tree a nodes may have at most two children. But if they have only one
children, or no children, the link part in the linked list representation remains null.
◻ In TBST representation, empty links can be reused by making some threads.
◻ If one node has some vacant left or right child area, that will be used as thread.

◻ Types : 1) Single (One-way) TBST


2) Double (Two-way/ Fully ) TBST.
Threaded BST (TBST)
101

◻ Single TBST has two variations:- Left and right threaded.


◻ Left threaded Single TBST :- if some node has no left child, then the left
pointer will point to its inorder predecesso
Threaded BST (TBST)
102

◻ Right threaded Single TBST: if some node has no right child, then the
right pointer will point to its inorder successor

◻ Demonstrates inorder order traversal using threads as below


Threaded BST (TBST)
Demonstrates inorder order traversal using threads as below
103
Threaded BST (TBST)
Demonstrates inorder order traversal using threads as below
104
Threaded BST (TBST)
105

◻ Double (Two-way/ Fully ) TBST: Where both left and right NULL pointers
are made to point to inorder predecessor and inorder successor
respectively.
◻ The predecessor threads are useful for reverse inorder traversal and
postorder traversal.
◻ The threads are also useful for fast accessing ancestors of a node.
Threaded BST (TBST)
Double (Two-way/ Fully) TBST: -
106

◻ Each node has five fields. Three fields like normal binary tree node,
another two fields to store Boolean value to denote whether link of that
side is actual link or thread.
◻ If no successor or predecessor is present, then it will point to header node.
Threaded BST (TBST)
Double (Two-way/ Fully) TBST: -
107
Threaded BST (TBST)
Double (Two-way/ Fully) TBST: -
108
Threaded BST (TBST)
Double (Two-way/ Fully) TBST: -
109
Threaded BST (TBST)
Double (Two-way/ Fully) TBST: -
110
Threaded BST - Operations
Insert, Delete, Search
111
Threaded BST - Operations
Insert, Delete, Search
112
Threaded BST - Operations
Insert, Delete, Search
113
Threaded BST - Operations
Insert, Delete, Search
114
Threaded BST - Operations
Insert, Delete, Search
115
Threaded BST- InOrder Traversal
116
Threaded BST- InOrder Traversal Algo
117

Algorithm Inorder(I)
{
ThreadedTreeNode *Header;
Header=I;
while(1)
{
I=fnFindInorder_Successor(H);
if(I==Header)
return;
else
print(I->info);
}
}
struct node
{
struct node *left;
boolean lthread;
int info;
boolean rthread;
struct node *right;
}
Threaded BST - Advantages
118

◻ In this Tree it enables linear traversal of elements.


◻ It eliminates the use of stack as it perform linear traversal, so save memory.
◻ Enables to find parent node without explicit use of parent pointer
◻ Threaded tree give forward and backward traversal of nodes by in-order
fashion
◻ Nodes contain pointers to in-order predecessor and successor
◻ For a given node, we can easily find inorder predecessor and successor. So,
searching is much more easier.
◻ In threaded binary tree there is no NULL pointer present. Hence memory
wastage in occupying NULL links is avoided.
◻ The threads are pointing to successor and predecessor nodes. This makes us to
obtain predecessor and successor node of any node quickly.
◻ There is no need of stack while traversing the tree, because using thread links we
can reach to previously visited nodes
Threaded BST - Disadvantages
119

◻ Every node in threaded binary tree need extra information(extra memory) to


indicate whether its left or right node indicated its child nodes or its inorder
predecessor or successor. So, the node consumes extra memory to implement.
◻ Insertion and deletion are way more complex and time consuming than the
normal one since both threads and ordinary links need to be maintained.
◻ Implementing threads for every possible node is complicated.
◻ Increased complexity: Implementing a threaded binary tree requires more
complex algorithms and data structures than a regular binary tree. This can
make the code harder to read and debug.
◻ Extra memory usage: In some cases, the additional pointers used to thread the
tree can use up more memory than a regular binary tree. This is especially true if
the tree is not fully balanced, as threading a skewed tree can result in a large
number of additional pointers.
Threaded BST - Disadvantages
120

◻ Limited flexibility: Threaded binary trees are specialized data structures that
are optimized for specific types of traversal. While they can be more efficient
than regular binary trees for these types of operations, they may not be as
useful in other scenarios. For example, they cannot be easily modified (e.g.
inserting or deleting nodes) without breaking the threading.
◻ Difficulty in parallelizing: It can be challenging to parallelize operations on a
threaded binary tree, as the threading can introduce data dependencies that
make it difficult to process nodes independently. This can limit the performance
gains that can be achieved through parallelism.
Threaded BST - Applications
121

◻ Expression evaluation: Threaded binary trees can be used to evaluate


arithmetic expressions in a way that avoids recursion or a stack. The tree can be
constructed from the input expression, and then traversed in-order or pre-order
to perform the evaluation.
◻ Database indexing: In a database, threaded binary trees can be used to index
data based on a specific field (e.g. last name). The tree can be constructed with
the indexed values as keys, and then traversed in-order to retrieve the data in
sorted order.
◻ Symbol table management: In a compiler or interpreter, threaded binary trees
can be used to store and manage symbol tables for variables and functions. The
tree can be constructed with the symbols as keys, and then traversed in-order or
pre-order to perform various operations on the symbol table.
◻ Disk-based data structures: It can be used in disk-based data structures (e.g.
B-trees) to improve performance. By threading the tree, it can be traversed in a
way that minimizes disk seeks and improves locality of reference.
Threaded BST - Applications
122

◻ Navigation of hierarchical data: In certain applications, threaded binary trees


can be used to navigate hierarchical data structures, such as file systems or web
site directories. The tree can be constructed from the hierarchical data, and then
traversed in-order or pre-order to efficiently access the data in a specific order.
Threaded BST - Time and Space Complexity
123

◻ The time complexity for insertion, deletion, and searching in a threaded binary
tree is the same as that of a BST, as we need to perform operations maximum
up to the depth of the tree. The depth of a threaded BST is
also log(n) where n is the total number of nodes in the tree

◻ Hence all operations take up O(log(n)) time complexity

◻ However, since we do not use any extra space for any of the operations, the
auxilliary space complexity is O(1)
Threaded BST - Revisited
124

◻ TBST is a type of binary tree data structure.


◻ Inorder traversal of a Binary tree can either be done using recursion or with
the use of a auxiliary stack.
◻ Idea : to make inorder traversal faster and do it without stack and without
recursion.
◻ Empty left and right child pointers in a binary tree are replaced with threads
that link nodes directly to their in-order predecessor or successor, and
provide way to traverse the tree without using recursion or a stack.
◻ A binary tree is made threaded by making all right child pointers that would
normally be NULL point to the inorder successor of the node (if it exists).
Topics
125

◻ Trees - Basic terminology, General tree, Representation


◻ Binary tree
properties
converting tree to binary tree
Operations on Binary tree
Tree Traversal Algorithms : Preorder, Inorder, Postorder Traversal
◻ Search Trees: Binary Search Trees (BST)
BST Operations
◻ Threaded BST (TBST)-
Thread concept & operations on TBST
◻ Huffman Encoding.
◻ Height Balanced Tree-
AVL Trees & operations on AVL tree,
◻ m-way Search Trees,
B-Tree,
B+ Tree.
Huffman Tree /Coding
126

◻ Compression unlike ASCII or Unicode encoding, which use the name number of
bits to encode each character,
◻ Huffman code uses different numbers of bits to encode the letters:
◻ More bits for rare letters, and fewer bits for common letters.
◻ Compression can be achieved further at words level and so on.
◻ Image compression/music compression/text compression/genomic sequence
compression
Huffman Tree /Coding
127

◻ It assigns codes to characters such that the length of the code depends on the
relative frequency or weight of the corresponding character.
◻ Huffman codes are of variable-length, and prefix-free (no code is prefix of
any other). Any prefix-free binary code can be visualized as a binary tree with
the encoded characters stored at the leaves.
◻ A Huffman coding tree or Huffman tree is a full binary tree in which
each leaf of the tree corresponds to a letter in the given alphabet.
◻ Define: the weighted path length of a leaf to be its weight times its depth.
◻ The Huffman tree is the binary tree with minimum external path weight, i.e.,
the one with the minimum sum of weighted path lengths for the given set of
leaves.
◻ So the goal is to build a tree with the minimum external path weight.
Huffman Tree /Coding
128

Steps to build Huffman Tree


1. Input is an array of unique characters along with their frequency of
occurrences and output is Huffman Tree.
2. Create a leaf node for each unique character and build a min heap of all
leaf nodes (Min Heap is used as a priority queue. The value of frequency
field is used to compare two nodes in min heap. Initially, the least frequent
character is at root)
3. Extract two nodes with the minimum frequency from the min heap.
4. Create a new internal node with a frequency equal to the sum of the two
nodes frequencies. Make the first extracted node as its left child and the other
extracted node as its right child. Add this node to the min heap.
5. Repeat steps#2 and #3 until the heap contains only one node. The remaining
node is the root node and the tree is complete.
Huffman Tree /Coding
129

◻ Huffman coding is a lossless data compression algorithm.


◻ The idea is to assign variable-length codes to input characters, lengths of
assigned codes are based on frequencies of corresponding characters
◻ The variable-length codes assigned to input characters are Prefix Codes, means
the codes (bit sequences) are assigned in such a way that the code assigned to
one character is not the prefix of code assigned to any other character.
◻ This is how Huffman Coding makes sure that there is no ambiguity when decoding
the generated bitstream.

There are mainly two major parts in Huffman Coding


◻ Build a Huffman Tree from input characters.
◻ Traverse the Huffman Tree and assign codes to characters
Huffman Tree /Coding
130
Huffman Tree /Coding
131
Huffman Tree /Coding
132
Huffman Tree /Coding
133
Huffman Tree /Coding
134
Topics
135

◻ Trees - Basic terminology, General tree, Representation


◻ Binary tree
properties
converting tree to binary tree
Operations on Binary tree
Tree Traversal Algorithms : Preorder, Inorder, Postorder Traversal
◻ Search Trees: Binary Search Trees (BST)
BST Operations
◻ Threaded BST (TBST)-
Thread concept & operations on TBST
◻ Huffman Encoding.
◻ Height Balanced Tree-
AVL Trees & operations on AVL tree,
◻ m-way Search Trees,
B-Tree,
B+ Tree.
Height Balanced Tree-
136
AVL Trees & operations on AVL tree
Height Balanced Tree-
137
AVL Trees & operations on AVL tree
Height Balanced Tree-
138
AVL Trees & operations on AVL tree
Height Balanced Tree-
139
AVL Trees & operations on AVL tree
Height Balanced Tree-
140
AVL Trees & operations on AVL tree
Height Balanced Tree-
141
AVL Trees & operations on AVL tree
Height Balanced Tree-
142
AVL Trees & operations on AVL tree
Height Balanced Tree-
143
AVL Trees & operations on AVL tree
Topics
144

◻ Trees - Basic terminology, General tree, Representation


◻ Binary tree
properties
converting tree to binary tree
Operations on Binary tree
Tree Traversal Algorithms : Preorder, Inorder, Postorder Traversal
◻ Search Trees: Binary Search Trees (BST)
BST Operations
◻ Threaded BST (TBST)-
Thread concept & operations on TBST
◻ Huffman Encoding.
◻ Height Balanced Tree-
AVL Trees & operations on AVL tree,
◻ m-way Search Trees,
B-Tree,
B+ Tree.
B Tree
A B tree of order m contains all the properties of an M way tree. In addition, it
contains the following properties.

Every node in a B-Tree contains at most m children.


Every node in a B-Tree except the root node and the leaf node
contain at least m/2 children.
The root nodes must have at least 2 nodes.
All leaf nodes must be at the same level.

You might also like