Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views87 pages

Chapter 3

Chapter Three discusses data structures, focusing on linked lists and their advantages over arrays, such as dynamic sizing and efficient memory usage. It describes various types of linked lists, including singly, doubly, and circular linked lists, along with their operations like insertion and deletion. The chapter also highlights applications of linked lists in implementing stacks, queues, and graphs.

Uploaded by

ambachewm27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views87 pages

Chapter 3

Chapter Three discusses data structures, focusing on linked lists and their advantages over arrays, such as dynamic sizing and efficient memory usage. It describes various types of linked lists, including singly, doubly, and circular linked lists, along with their operations like insertion and deletion. The chapter also highlights applications of linked lists in implementing stacks, queues, and graphs.

Uploaded by

ambachewm27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 87

Chapter Three

Data structures and applications

1
Introduction
 A linked list is a way to store a collection of elements. Like an array these can be character or integers.
Each element in a linked list is stored in the form of a node.
 Node is a collection of two sub-elements or parts. A data part that stores the element and a next part
that stores the link to the next node.
 A linked list is formed when many such nodes are linked together to form a chain. Each node points to
the next node present in the order. The first node is always used as a reference to traverse the list and is
called HEAD. The last node points to NULL.
 Declaring a Linked list:
In C++ language, a linked list can be implemented using structure and pointers.
struct node{
int data;
struct node *next;
};

2
Array
 Array is a collection of Elements
Vs Linked List
 Arrays are Simple and fast but we must specify their size at construction time. This has its own
drawbacks. If you construct an array with space for n, Tomorrow you need n+1. Here comes a need for
a more flexible system. So, to overcome the drawback of Array the concept of linked list is released.
 We cannot upgrade the size of the array, But the size of Linked list is flexible.
 In case of array, we can not add or reduce memory, But the reverse is true in Linked list.
Advantages of Linked List
 Flexible space used by dynamically allocating space for each element as needed. This implies that one
need not know the size of the list in advance. Memory is Efficiently utilized.
 A Linked List is made up of a chain of nodes. each node contains
1. The data item, and
2. A pointer to the next node

3
Cont’d…
 An array is a very useful data structure provided in programming languages. However, it has at
least two limitations:
1.Its size has to be known at compilation time and
2.The data in the array are separated in computer memory by the same distance, which means that
inserting an item inside the array requires shifting other data in this array.
 This limitation can be overcome by using linked structures. A linked structure is a collection of
nodes storing data and links to other nodes.
 In this way, nodes can be located anywhere in memory, and passing from one node of the linked
structure to another is accomplished by storing the addresses of other nodes in the linked
structure.
 Although linked structures can be implemented in a variety of ways, the most flexible
implementation is by using pointers.

4
Cont’d…

5
Cont’d…
 A Linked list is basically a data structure for storing a collection of items.
 But an array can be visualize as a long box with many partitions of the same size.
 A Linked list can be visualize as many boxes that are connected to each other.
 Each of this boxes in a linked list can be represented as an object and lets say the class for the
object is called Box which have two fields, Data and Next (Next Box).

6
Cont’d…
 In Linked List a sequence of element is called Nodes

7
Types of Linked List
 There are three types of Linked List, Those are:
1.Singly Linked List:- Navigation is Forward Only
2.Doubly Linked List:- Forward and Backward Navigation is Possible
3.Circular Linked List:- Last Element is Linked to the First Element

8
1. Singly Linked List
 A Single Linked List is a list made up of nodes that consists of two parts
A.Data:- Contains the actual data
B.Link:- Contains the address of the next node of the list
 Linked Lists are the most basic self-referential (indicate or hold itself or itself
holds his own address) structures.
 Linked Lists Allow you to have a chain of structs(keyword for Structure) with
related data.

9
Self Referential Structures
 Generally Nodes of linked lists are examples of self referential structures-which refer to memory
location of same type by storing a self type pointer as a member.
 Structures can hold pointers to instances of themselves.
struct list {
char name [10];
int count;
struct list *next;
}
;
 However, structures cannot contains instances of themselves
 N.B Nodes are lists, for example the above Psdocode there are three lists or Nodes. Those are
Name, Count, and Next or Pointer.

10
Creating Linked Lists in C++
 A Linked List is a data structure that is built from structures and pointers. It forms a chain of
“Nodes” with pointers representing the links of the chain and holding the entire thing together.
A Linked List can be represented by a diagram as follows:
 This Linked lists has four nodes in it, each with a link to the next node in the series. The last
node has a link to a special value NULL, which any pointer(whatever its type) can point to it,
to show that it is the last link in the chain.
 There are also another special pointer called Start (also called Head), which points to the first
link in the chain that we can keep track of it.

11
Cont’d…

Data Field
//Actual data
will be stored

Address Field
// Holds the address
of the next node
12
Psdocode for Singly Linked List

13
Cont’d…
The following diagram shows the structure of a singly linked list.

14
Cont’d…
 As shown above, the first node of the linked list is called “head” while the last node is called “Tail”.
As we see, the last node of the linked list will have its next pointer as null since it will not have any
memory address pointed to. Since each node has a pointer to the next node, data items in the linked
list need not be stored at contiguous locations.
 The nodes can be scattered in the memory. We can access the nodes anytime as each node will have
an address of the next node. We can add data items to the linked list as well as delete items from the
list easily.
 Thus it is possible to grow or shrink the linked list dynamically. There is no upper limit on how
many data items can be there in the linked list. So as long as memory is available, we can have as
many data items added to the linked list.
 Apart from easy insertion and deletion, the linked list also doesn’t waste memory space as we need
not specify beforehand how many items we need in the linked list. The only space taken by linked
list is for storing the pointer to the next node that adds a little overhead.

15
Operations
 Just like the other data structures, we can perform various operations for the linked list
as well. But unlike arrays, in which we can access the element using subscript directly
even if it is somewhere in between, we cannot do the same random access with a
linked list.

1. Insertion
 Insertion operation of linked list adds an item to the linked list. Though it may sound
simple, given the structure of the linked list, we know that whenever a data item is
added to the linked list, we need to change the next pointers of the previous and next
nodes of the new item that we have inserted.

16
Cont’d…
 There are three positions in the linked list where a data item can be added.
I.At the beginning of the linked list
A linked list is shown below 2->4->6->8->10.
 If we want to add a new node 1, as the first node of the list, then the head pointing to node 2
will now point to 1 and the next pointer of node 1 will have a memory address of node 2 as
shown in the below figure.

17
Thus the new linked list becomes 1->2->4->6->8->10.
Cont’d…
struct Node
{
int data;
struct Node *next;
};
//insert a new node in front of the list
void push(struct Node** head, int node_data)
{
struct Node* newNode = new Node; // 1. Create and allocate node
newNode->data = node_data; // 2. Assign data to node
newNode->next = (*head);// 3. Set next of new node as head
(*head) = newNode; //4. Move the head to point to the new node
}

18
II. After the given Node
Here, a node is given and we have to add a new node after the given
node.
In the below-linked list a->b->c->d ->e, if we want to add a node f after
node c then the linked list will look as follows:

19
Cont’d…
 Thus in the above diagram, we check if the given node is present. If it’s present, we create a new node f. Then we point the
next pointer of node c to point to the new node f. The next pointer of the node f now points to node d.
//insert new node after a given node
void insertAfter(struct Node* prev_node, int node_data)
{
//1. check if the given prev_node is NULL
if (C == NULL)
{
cout<<"the given pr0evious node is required,cannot be NULL"; return;
}
struct Node* f =new Node; // 2. Create and allocate new node
f->data = node_data; // 3. assign data to the node
f->next = C->next; //4. Make next of new node as next of prev_node
C->next = f; //5. move the next of prev_node as new_node
}

20
III. At the end of the Linked List
 In the third case, we add a new node at the end of the linked list. Consider we have the same
linked list a->b->c->d->e and we need to add a node f to the end of the list. The linked list
will look as shown below after adding the node.

 Thus we create a new node f. Then the tail pointer pointing to null is pointed to f and the next
pointer of node f is pointed to null.

21
2. Deletion
 Like insertion, deleting a node from a linked list also involves various positions
from where the node can be deleted.
 We can delete the first node, last node or a random kth node from the linked list.
 After deletion, we need to adjust the next pointer and the other pointers in the
linked list appropriately so as to keep the linked list intact/undamaged/.

22
Cont’d…

23
Applications
 As arrays and linked lists are both used to store items and are linear data structures, both
these structures can be used in similar ways for most of the applications.
Some of the applications for linked lists are as follows:
 A linked list can be used to implement stacks and queues.
 A linked list can also be used to implement graphs whenever we have to represent graphs as
adjacency lists.
 A mathematical polynomial can be stored as a linked list.
 In the case of hashing technique, the buckets used in hashing are implemented using the
linked lists.
 Whenever a program requires dynamic allocation of memory, we can use a linked list as
linked lists work more efficiently in this case

24
2. Doubly linked lists
 A doubly linked list is a variation of the singly linked list. We are aware that the
singly linked list is a collection of nodes with each node having a data part and a
pointer pointing to the next node.
 A doubly linked list is also a collection of nodes. Each node here consists of a
data part and two pointers.
 One pointer points to the previous node while the second pointer points to the
next node.
 As in the singly linked list, the doubly linked list also has a head and a tail.
 The previous pointer of the head is set to NULL as this is the first node. The
next pointer of the tail node is set to NULL as this is the last node.

25
Cont’d…

 In the above figure, we see that each node has two pointers, one pointing to the previous
node and the other pointing to the next node. Only the first node (head) has its previous node
set to null and the last node (tail) has its next pointer set to null.
 As the doubly linked list contains two pointers i.e. previous and next, we can traverse it into
the directions forward and backward. This is the main advantage of doubly linked list over
the singly linked list.

26
Cont’d…
Declaration
In C++ style declaration, a node of the doubly linked list is represented as
follows:
struct node
{
struct node *prev;
int data;
struct node *next;
};

27
Insertion
 Insertion operation of the doubly linked list inserts a new node in the linked list. Depending on the
position where the new node is to be inserted, we can have the following insert operations.
 Insertion at front – Inserts a new node as the first node.
 Insertion at the end – Inserts a new node at the end as the last node.
 Insertion before a node – Given a node, inserts a new node before this node.
 Insertion after a node – Given a node, inserts a new node after this node.

Deletion
 Deletion operation deletes a node from a given position in the doubly linked list.
 Deletion of the first node – Deletes the first node in the list
 Deletion of the last node – Deletes the last node in the list.
 Deletion of a node given the data – Given the data, the operation matches the data with the node data in the
linked list and deletes that node.

28
Traversal
 Traversal is a technique of visiting each node in the linked list. In a doubly linked list, we
have two types of traversals as we have two pointers with different directions in the doubly
linked list.
1. Forward traversal – Traversal is done using the next pointer which is in the forward
direction.
2. Backward traversal – Traversal is done using the previous pointer which is the
backward direction.

29
Insertion
 Insert a node at the front

 Insertion of a new node at the front of the list is shown above. As seen, the previous new
node N is set to null. Head points to the new node. The next pointer of N now points to
N1 and previous of N1 that was earlier pointing to Null now points to N.

30
Cont’d…

31
Deletion
 A node can be deleted from a doubly linked list from any position like from the
front, end or any other given position or given data.
Algorithm
1. If node to be deleted is head node, then change the head pointer to point to
next current head
2. Set next pointer of previous to node to be deleted, if previous exists
3. Set previous of next to node to be deleted, if next exists
 When deleting a node from the doubly linked list, we first reposition the pointer
pointing to that particular node so that the previous and after nodes do not have
any connection to the node to be deleted. We can then easily delete the node.

32
Cont’d…
 Consider the following doubly linked list with three nodes A, B, C. Let us consider that we
need to delete the node B.

33
Cont’d…
 As shown in the above series of the diagram, we have demonstrated the
deletion of node B from the given linked list. The sequence of operation
remains the same even if the node is first or last.
 The only care that should be taken is that if in case the first node is deleted, the
second node’s previous pointer will be set to null.
 Similarly, when the last node is deleted, the next pointer of the previous node
will be set to null.
 If in between nodes are deleted, then the sequence will be as above.
 We leave the program to delete a node from a doubly linked list. Note that the
implementation will be on the lines of the insertion implementation.

34
Advantages
 The doubly linked list can be traversed in forward as well as backward directions, unlike singly
linked list which can be traversed in the forward direction only.
 Delete operation in a doubly-linked list is more efficient when compared to singly list when a given
node is given. In a singly linked list, as we need a previous node to delete the given node, sometimes
we need to traverse the list to find the previous node. This hits the performance.
 Insertion operation can be done easily in a doubly linked list when compared to the singly Linked list.
Disadvantages:
 As the doubly linked list contains one more extra pointer i.e. previous, the memory space taken up by
the doubly linked list is larger when compared to the singly linked list.
 Since two pointers are present i.e. previous and next, all the operations performed on the doubly
linked list have to take care of these pointers and maintain them thereby resulting in a performance
bottleneck.

35
Applications of Doubly Linked List
 A doubly linked list can be applied in various real-life scenarios and applications as
discussed below.
A Deck of cards in a game is a classic example of a doubly linked list. Given that each
card in a deck has the previous card and next card arranged sequentially, this deck of
cards can be easily represented using a doubly linked list.
Browser history/cache – The browser cache has a collection of URLs and can be
navigated using the forward and back buttons is another good example that can be
represented as a doubly linked list.
Most recently used (MRU) also can be represented as a doubly linked list.
Other data structures like Stacks, hash table, the binary tree can also be constructed or
programmed using a doubly linked list.

36
3. Circular lists
 A circular linked list is a variation of the linked list. It is a linked list whose nodes are
connected in such a way that it forms a circle.
 In the circular linked list, the next pointer of the last node is not set to null but it contains the
address of the first node thus forming a circle.
Circular Linked List
 The arrangement shown below is for a singly linked list

 A circular linked list can be a singly linked list or a doubly linked list. In a doubly circular
linked list, the previous pointer of the first node is connected to the last node while the next
pointer of the last node is connected to the first node.
37
Cont’d…
 Its representation is shown below.

 N.B:- Every node has two fields one is the data field another is the address field, So if that
particular node is last node, it is not establishing a link with another node, that is why we will
place NULL in the last node.
 In a Single linked list, If the address field of the last node holds the address field of Head,
Then this is called Circular Linked list. 38
Cont’d…

39
Declaration
We can declare a node in a circular linked list as any other node as shown below:
struct Node
{
int data;
struct Node *next;
};
In order to implement the circular linked list, we maintain an external pointer “last” that points to the
last node in the circular linked list. Hence last->next will point to the first node in the linked list.
By doing this we ensure that when we insert a new node at the beginning or at the end of the list, we
need not traverse the entire list. This is because the last points to the last node while last->next points
to the first node. This wouldn’t have been possible if we had pointed the external pointer to the first
node.

40
Traversal
 Traversal is a technique of visiting each and every node. In linear linked lists like singly
linked list and doubly linked lists, traversal is easy as we visit each node and stop when
NULL is encountered.
 However, this is not possible in a circular linked list. In a circular linked list, we start from the
next of the last node which is the first node and traverse each node.
 We stop when we once again reach the first node.

41
Advantages
 We can go to any node and traverse from any node. We just need to stop when we visit the
same node again.
 As the last node points to the first node, going to the first node from the last node just takes
a single step.
Disadvantages:
 Reversing a circular linked list is cumbersome.
 As the nodes are connected to form a circle, there is no proper marking for beginning or
end for the list. Hence, it is difficult to find the end of the list or loop control. If not taken
care, an implementation might end up in an infinite loop.
 We cannot go back to the previous node in a single step. We have to traverse the entire list
from first.

42
Applications of Circular Linked List
 Real-time application of circular linked list can be a multi-programming operating system
wherein it schedules multiple programs.
 Each program is given a dedicated timestamp to execute after which the resources are passed
to another program. This goes on continuously in a cycle.
 This representation can be efficiently achieved using a circular linked list.
 Games that are played with multiple players can also be represented using a circular linked
list in which each player is a node that is given a chance to play.
 We can use a circular linked list to represent a circular queue. By doing this, we can remove
the two pointers front and rear that is used for the queue.
 Instead, we can use only one pointer.

43
Chapter 4
Stacks and Queues

44
Introduction
 Both Stack and Queue are under the category of Linear data structure
 In Linear data structure, values are arrange in linear fashion.
 Stack: Add to top and remove from top
 Queue: Add to back and remove from front
 In this chapter, we will see the concept of Stack and Queue one by one:

45
Stack
 A simple data structure, in which insertion and deletion occur at the same end, is termed
(called) a stack. It is a LIFO (Last In First Out) structure.
 The operations of insertion and deletion are called PUSH and POP Respectively.
 Push - push (put) item onto stack
 Pop - pop (get) item from stack
 Stack is a Linear data structure working in LIFO manner.
 It is an Abstract Data type (ADT), commonly used in most programming Languages.
 In this type of data structure, we can extract the data from the end from which we enter the
data.
 Push Operation is used to enter data in stack and Pop Operation is used to remove data
from the stack.

46
Cont’d…
 Common terminology or Commands that we use in stacks:
Push(Item):To add an Element to the stack
Pop: To remove an Element from the stack
isEmpty: Return true If the stack is Empty Else return False
isFull: Return true If the stack is Full Else return False

47
Stack- Examples

48
Stack Representation

49
Cont’d…

50
Cont’d…
 We need to know TOS(Top of Stack)
 Operations done on stack
 Push--- Insert Element at TOS
 Pop---Remove Element from TOS

51
Cont’d…

52
Algorithm for Insert Data in to a Stack

 Step 1:- Check Stack is Full


If Top=Max-1
Print Stack is Full and exit
 Step 2:- Increment to by one
TOP=TOP+1
 Step 3:- Insert Data in to stack
Stack[TOP]=data
 Step 4:- End

53
Push(Insert data Item into Stack)
 For Inserting data Item into Stack, we use Push Operation.
 Data 1, Data 2, Data 3, Data 4

54
Algorithm for Remove Data from Stack
 Step 1:- Check Stack is Empty
If Top= -1
Print Stack is Empty and exit
 Step 2:- Delete an Element from stack Top
Set Del_element=Stack[TOP]
 Step 3:- Decrement stack size by one
TOP=TOP-1
 Step 4:- End

55
Pop(Deleting data Item from Stack)
 For Deleting data Item from Stack, we use pop Operation.
 Data 1, Data 2, Data 3, Data 4

56
Stack-Implementation
 Stacks can be Implemented both as an Array (Contiguous list) and as a Linked List.
 We want a set of Operations that will work with either a type of Implementation: i.e the method of Implementation is
Hidden and can be changed without affecting the programs that use them.
Push()
{
If there is a room // If there is a Space
{
Put an Item on the top of the Stack
}
Else
{
Give an Error message //Stack Overflow or Stack already full
}}

57
Cont’d…
Pop()
{
If stack not empty //If the stack Contains an Element or not
{
Return the value of the top Item to the user and remove the top item from the stack
}
Else
{
Give an Error message //Stack is underflow
}}

58
Application of Stacks
1. Evaluation of Algebraic Expressions
 Re-expressing the Expression(in the form of easily understandable by the compiler):- In order to
solve Arithmetic Expressions, Computers restructure them so that the results of each computation are
incorporated within the Expression. Once transformed, an Expression can be solved one step.
Types of Expression
 The normal (or human) way of expressing mathematical expressions is called infix form, e.g.
4+5*5. i.e Ans=29
 However, there are other ways of representing the same expression, either by writing all
operators before their operands or after them,
 e.g.
4 5 5 * + //N.B 4,5,5 is called Operands and +,*,= is called Operators
+4*55

59
Cont’d…
455*+
In this case If the Operand comes before the Operator (* and +) we call it postfix.
+4*55
In this case If the Operator comes before the Operand (+ and *) we call it Prefix.
But If the Operator comes between the Operand like 4+5*5, we call it Infix: it is natural or
mire adapted by human beings.
Postfix and Prefix Notations like:
455*+
+4*55
This method is called Polish Notation (because this method was discovered by the Polish
mathematician Jan Lukasiewicz).

60
Cont’d…
 When the operators are written before their operands, it is called the Prefix form. This
means that At least one Operator comes before the Operand, but In between there may by
another operators.
• e.g. + 4 * 5 5
 When the operators come after their operands, it is called Postfix form (suffix form or
reverse polish notation). This means that At least one Operator comes after the Operand, but I
between there may by another operators.
• e.g. 4 5 5 * +

61
Cont’d…
The valuable aspect of RPN (Reverse Polish Notation or postfix )
Parentheses are unnecessary or ()
Easy for a computer (compiler) to evaluate an arithmetic expression Postfix (Reverse
Polish Notation)
Postfix notation arises from the concept of post-order traversal of an expression tree ( this
concept will be covered when we look at trees).
For now, consider postfix notation as a way of redistributing operators in an expression so that
their operation is delayed until the correct time.

62
Purpose of Postfix
 Infix Notation cannot be used to evaluate expressions in high level Languages.
 To decide how to assess an expression, we must first analyze it.
 An approach that is frequently used is to transform an Infix Notation to Postfix Notation before evaluating It.

Syntax
 Operands are Immediately sent to the Output.
 The stack is pushed using Operators, including Parentheses.
 Determine whether the current Operator is less than the stack top Operator, If the top operator is less than,
Place the current operator on the stack.
 Current Operator is pushed into the stack and the top operator is popped if the top operator is bigger than (or
equal to) the current
 Pop from the stack until we finish a matching left parentheses if we come across a right parentheses. Don’t
print Parentheses.// Don’t store parentheses in the output

63
Cont’d…
Operator Priority in Order of Precedence:
1.Parentheses() have high priority
2.All Unary Operators(sine, cosine..)
3.Division and Multiplication / *…if they come once= perform Left to write
4.Addition and Subtraction + - …if they come once= perform Left to write

64
Queues
 A Data structure that has access to its data at the front and rear/back/.
 Operates on FIFO (Fist In First Out) basis.
 LILO Refers to Last In, Last Out Equivalent to FIFO
 Uses two pointers/indices to keep track of information/data (i.e front and rear)
Has two basic operations:
 Enqueue - inserting data at the rear of the queue
 Dequeue – removing data at the front of the queue

OR
65
Cont’d…
 Example:

66
Simple array implementation of enqueue
 Analysis:
and dequeue operations
 Consider the following structure: int Num[MAX_SIZE];// Num is name of queue
 We need to have two integer variables that tell:
1.The index of the front element //to show the exact location of front
2.The index of the rear element //to show the exact location of front
 We also need an integer variable that tells: // total size of the queue
the total number of data in the queue
 int FRONT =-1,REAR =-1;
 At the very beginning we should declare locally or globally Front=-1 & Rear=-1
 Since we don’t add any data to the queue F & R=-1, B/C there is no Index less than 0.
 int QUEUESIZE=0; // There is no any element in the queue

67
To enqueue data to the queue
 Check if there is a space in the queue
 REAR<MAX_SIZE-1? // MAX_SIZE=N=total Element
Yes/True: Increment REAR
• Store the data in Num[REAR]
• Increment QUEUESIZE
• FRONT = = -1? // initially it was no data, so increment the
Front by 1. i.e -1+1=0. our front is at 0 index
• Yes: - Increment FRONT // from -1 to 0
No/False: - Queue Overflow // no space in the queue, If we add new data
Overflow will occur

68
To dequeue data to the queue
 Check if there is data in the queue
 QUEUESIZE > 0 ?
 Yes: - Copy the data in Num[FRONT]
• Increment FRONT
• Decrement QUEUESIZE
 No: - Queue Underflow // There is no data in the queue

69
const int MAX_SIZE=100;
Implementation
int FRONT =-1, REAR =-1;
int QUEUESIZE = 0;
void enqueue(int x)
{
if(Rear<MAX_SIZE-1)
{
REAR++;
Num[REAR]=x;
QUEUESIZE++;
if(FRONT = = -1)
FRONT++;
}
else
cout<<"Queue Overflow";
}

70
Cont’d…
int dequeue()
{
int x;
if(QUEUESIZE>0)
{
x=Num[FRONT];
FRONT++;
QUEUESIZE--;
}
else
cout<<"Queue Underflow";
return(x);
}
71
Chapter 5
Tree

72
Introduction
 The Tree is a nonlinear hierarchical data structure and comprises a collection of
entities known as nodes.
 It connects each node in the tree data structure using "edges”, both directed and
undirected.
 A Tree can also be defined as a collection of Entities (nodes) linked together to simulate a
hierarchy.

73
Why Tree Data Structure
1. A Linear data structure always stores the data elements in a sequential form
2. In operation Performed in the linear data structure, the time complexity increases as the data
size increases.
For example, if the elements are stored in a linear form, one data element is at the first
place and another data element is at the last place.
Imagine you want to access the last data element, then in the traversal you had to start
from the first position and move sequentially and slowly at the end is last data element.
Accessing that particular element is really time consuming. So, if we have huge data
elements it is Difficult.
3. The tree data structure is non-Linear, Allows Easier and quicker access to the data element

74
Tree Terminology
 Consider the following Tree. ABEFGCDHIJKLM

75
 Root:- a Node without a parent A
Cont’d…
 In a tree data structure, the root is the first node of the tree. The root node is the initial node of the tree in data
structures.
 In the tree data structure, there must be only one root node.
 Edge:- Link Between two Nodes
 In a tree in data structures, the connecting link of any two nodes is called the edge of the tree data structure.
 In the tree data structure, N number of nodes connecting with N -1 number of edges.
 Parent:- The Immediate predecessor of any node.
 In the tree in data structures, the node that is the predecessor of any node is known as a parent node, or a node with a
branch from itself to any other successive node is called the parent node. Roots not having any parent node.
 Child:- The Immediate successor of any node.
 The node, a descendant of any node, is known as child nodes in data structures.
 In a tree, any number of parent nodes can have any number of child nodes.
 In a tree, every node except the root node is a child node.

76
Cont’d…

77
Cont’d…
 Subtree:- A tree consisting of a node and its Descendants.

 Binary Tree:- a tree in which each node has at most two children called Left and
right Children.

78
Types of Tree
 There are Four different types of trees. Those are given below:

79
1.Binary tree
 A binary tree is a tree data structure in which each parent node has at most two
children.
 It might have one or more than one but not more than two children.

80
Types of Binary Tree
 Full binary tree: a binary tree where each node has either 0 or 2 children.

 Balanced binary tree: a binary tree where each node except the leaf nodes has
left and right children and all the leaf nodes are at the same level.

81
2. Binary Search Tree
 A Binary search tree or BST is a tree data structure in which each node has a
maximum of two children.
 All nodes of the left subtree are less than the root node.
 All nodes of the right subtree are more than the root node.

82
3. AVL Tree

83
4. B-Tree
 B tree is a special kind of self-balancing search tree in which each node can
contain more than one key and can have more than two children.
 B tree is also Known as a height-balanced m-way tree

84
Tree Traversal
 Traversing tree helps to visit required node in the tree to perform specific function.
 Tree traversal can be performed by three ways:
1.Pre-order traversal: traversing binary tree in the order of root, left and right.
First, Visit root node
Visit all nodes from the left side
Visit all the nodes from the right side
2.In-order traversal: traversing binary tree in the order of left, root and right.
First, Visit all nodes from the left side
Visit root node
Visit all nodes from the right side
3.Post-order traversal: traversing binary tree in the order of left, right and root.
First, Visit all nodes from the left side
Visit all nodes from the right side
Visit root node

85
Cont’d…

86
Application of Trees
1. Binary Search Trees are used to quickly check whether an element present in
a set or not.
2. Most popular database uses B-tree, which is a variant of tree data structure.
3. Modified version of Trees called Tries used in the router, to store routing
Information.
4. The compiler uses a syntax tree to validate the syntax of every program you
write

87

You might also like