0% found this document useful (0 votes)
17 views33 pages

Ds Mod 3

Uploaded by

xcr6p6ysq7
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)
17 views33 pages

Ds Mod 3

Uploaded by

xcr6p6ysq7
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/ 33

MODULE III

NON LINEAR DATASTRUCTURES

o A non-linear data structure is another important type in which data elements


are not arranged sequentially; mainly, data elements are arranged in random
order without forming a linear structure.
o Data elements are present at the multilevel, for example, tree.
o In trees, the data elements are arranged in the hierarchical form, whereas in
graphs, the data elements are arranged in random order, using the edges and
vertex.
o Multiple runs are required to traverse through all the elements completely.
Traversing in a single run is impossible to traverse the whole data structure.
o Each element can have multiple paths to reach another element.
o The data structure where data items are not organized sequentially is called a
non-linear data structure. In other words, data elements of the non-linear
data structure could be connected to more than one element to reflect a special
relationship among them.

Trees and Graphs are the types of non-linear data structures.

Properties of Non-linear data structures

o It is used to store the data elements combined whenever they are not present
in the contiguous memory locations.
o It is an efficient way of organizing and properly holding the data.
o It reduces the wastage of memory space by providing sufficient memory to
every data element.

1
o Unlike in an array, we have to define the size of the array, and subsequent
memory space is allocated to that array; if we don't want to store the elements
till the range of the array, then the remaining memory gets wasted.
o So to overcome this factor, we will use the non-linear data structure and have
multiple options to traverse from one node to another.
o Data is stored randomly in memory.
o It is comparatively difficult to implement.
o Multiple levels are involved.
o Memory utilization is effective.

TREE

o The tree is a non-linear data structure that is comprised of various nodes. The
nodes in the tree data structure are arranged in hierarchical order.

o It consists of a root node corresponding to its various child nodes, present at


the next level. The tree grows on a level basis, and root nodes have limited
child nodes depending on the order of the tree.
o For example, in the binary tree, the order of the root node is 2, which means
it can have at most 2 children per node, not more than it.
o The non-linear data structure cannot be implemented directly, and it is
implemented using the linear data structure like an array and linked list.
o The tree itself is a very broad data structure and is divided into various
categories like Binary tree, Binary search tree, AVL trees, Heap, max
Heap, min-heap, etc.
o All the types of trees mentioned above differ based on their properties.

2
o Unlike Arrays, Stack, Linked Lists, and queues, which are linear data
structures, trees are hierarchical.

o A tree data structure is a collection of objects or entities known as nodes linked


together to represent or simulate hierarchy.
o This data is not arranged in a sequential contiguous location like as we have
observed in an array, the homogeneous data elements are placed at the
contiguous memory location so that the retrieval of data elements is simpler.
o A tree data structure is non-linear because it does not store sequentially. It is
a hierarchical structure as elements in a Tree are arranged in multiple levels.
o The topmost node in the Tree data structure is known as a root node. Each
node contains some data, and data can be of any type. The node contains the
employee's name in the tree structure, so the data type would be a string.
o Each node contains some data and the link or reference of other nodes that
can be called children.

BINARY TREE
3
• It is a very important subcategory of simple trees. As the name suggests, we
can easily predict that the binary tree is consists of two children only.
• A binary tree comprises nodes that can have two children, as described by the
word "binary," which means "two numbers." Any node can have a maximum
of 0, 1, or 2 nodes in a binary tree.
• A tree whose elements have at most 2 children is called a binary tree. Since
each element in a binary tree can have only 2 children, we typically name
them the left and right children. They are most commonly used in data
structures for two reasons:

For obtaining nodes and categorizing them, as observed in Binary Search Trees.

For representing data through a bifurcating structure.

BASIC TERMINOLOGIES OF TREES


1. Root node: The tree consists of a root node; it is the starting node of the tree
from which any tree grows. The root node is present at level 0 in any tree.
Depending on the order of the tree, it can hold that much of child nodes. For
example, if in a tree the order is 3, then it can have at most three child nodes,
and minimum, it can have 0 child nodes.
2. Parent node: The converse notion of a child.
3. Child node: The child node is the node that comes after the root node, which
has a parent node and has some ancestors. It is the node present at the next
level of its parent node. For example, if any node is present at level 5, it is
sure that its parent node is present at level 4, just above its level.
4. Edge: Edges are nothing but the link between the parent node, and the
children node is called the link or edge connectivity between two nodes.

4
5. Siblings: The nodes having the same parent node is called siblings of each
other. Same ancestors are not siblings, and only the parent node must be the
same, defined as siblings. For example, if node A has two child nodes, B and
C, B and C are called siblings.
6. Leaf node: The leaf node is the node that does not have any child nodes. It is
the termination point of any tree. It is also known as External nodes.
7. Degree of a node: The degree of a node is defined as the number of children
nodes. The degree of the leaf node is always 0 because it does not have any
children, and the internal node always has atleast one degree, as it contains
atleast one child node.
8. Height of the tree: The tree's height is defined as the distance of the root node
to the leaf node present at the last level is called the height of the tree. In other
words, height is the maximum level upto which the tree is extended.
9. Descendant – A node reachable by repeated proceeding from parent to child.
10. Ancestor – A node reachable by repeated proceeding from child to parent.
11. Internal node – A node with at least one child.
12. External node – A node with no children.
13. Degree of a tree– Number of sub trees of a node.
14. Path – A sequence of nodes and edges connecting a node with a descendant.
15. Path length- Total number of nodes in that path.
16. Level – The level of a node is defined by 1 + (the number of connections
between the node and the root).
17. Height of node – The height of a node is the number of edges on the longest
downward path between that node and a leaf.
18. Depth of a node– The depth of a node is the number of edges from the node
to the tree's root node.

5
19. Depth of a tree-The total number of edges from the root node to the
leaf node in the longest path is known as "Depth of Tree".
20. Forest – A forest is a set of n ≥ 0 disjoint trees.

TYPES OF BINARY TREES

1. Full Binary Tree

A full Binary tree is a special type of binary tree in which every parent
node/internal node has either two or no children.

Full Binary Tree

2. Perfect Binary Tree

A perfect binary tree is a type of binary tree in which every internal node has
exactly two child nodes and all the leaf nodes are at the same level.

Perfect Binary Tree

3. Complete Binary Tree

6
A complete binary tree is just like a full binary tree, but with two major differences

1. Every level must be completely filled

2. All the leaf elements must lean towards the left.

3. The last leaf element might not have a right sibling i.e. a complete binary tree
doesn't have to be a full binary tree.

Complete Binary Tree

4. Degenerate or Pathological Tree

A degenerate or pathological tree is the tree having a single child either left or
right.

Degenerate Binary Tree


5. Skewed Binary Tree

7
A skewed binary tree is a pathological/degenerate tree in which the tree is either
dominated by the left nodes or the right nodes. Thus, there are two types of skewed
binary tree: left-skewed binary tree and right-skewed binary tree.

Skewed Binary Tree


6. Balanced Binary Tree

It is a type of binary tree in which the difference between the height of the left and
the right subtree for each node is either 0 or 1.

Balanced Binary Tree

Eg:

8
Example of Balanced and Unbalanced Binary

BINARY TREE REPRESENTATIONS

A binary tree data structure is represented using two methods. Those methods are as
follows...

1. Array Representation
2. Linked List Representation

Consider the following binary tree...

9
1. Array Representation of Binary Tree

In array representation of a binary tree, we use one-dimensional array (1-D Array)


to represent a binary tree.
Consider the above example of a binary tree and it is represented as follows...

To represent a binary tree of depth 'n' using array representation, we need one
dimensional array with a maximum size of 2n + 1.

2. Linked List Representation of Binary Tree

We use a double linked list to represent a binary tree. In a double linked list, every
node consists of three fields. First field for storing left child address, second for
storing actual data and third for storing right child address.
In this linked list representation, a node has the following structure...

10
The above example of the binary tree represented using Linked list representation is
shown as follows...

BINARY SEARCH TREE(BST)

A binary search tree follows some order to arrange the elements. In a Binary search
tree, the value of left node must be smaller than the parent node, and the value of
right node must be greater than the parent node. This rule is applied recursively to
the left and right subtrees of the root.

Advantages of Binary search tree

o Searching an element in the Binary search tree is easy as we always have a


hint that which subtree has the desired element.

11
o As compared to array and linked lists, insertion and deletion operations are
faster in BST.

In a binary search tree, all the nodes in the left subtree of any node contains smaller
values and all the nodes in the right subtree of any node contains larger values as
shown in the following figure...

Example

The following tree is a Binary Search Tree. In this tree, left subtree of every node
contains nodes with smaller values and right subtree of every node contains larger
values.

12
Every binary search tree is a binary tree but every binary tree need not to be
binary search tree.

OPERATIONS ON BINARY SEARCH TREE

The following operations are performed on a binary search tree...

1. Search
2. Insertion
3. Deletion
4. Traversal

1. Search Operation in BST

The search operation is performed as follows...

• Step 1 - Read the search element from the user.


• Step 2 - Compare the search element with the value of root node in the tree.
• Step 3 - If both are matched, then display "Given node is found!!!" and
terminate the function
• Step 4 - If both are not matched, then check whether search element is smaller
or larger than that node value.
• Step 5 - If search element is smaller, then continue the search process in left
subtree.
• Step 6- If search element is larger, then continue the search process in right
subtree.
• Step 7 - Repeat the same until we find the exact element or until the search
element is compared with the leaf node
• Step 8 - If we reach to the node having the value equal to the search value
then display "Element is found" and terminate the function.
13
• Step 9 - If we reach to the leaf node and if it is also not matched with the
search element, then display "Element is not found" and terminate the
function.

Now, let's understand the searching in binary tree using an example. We are taking
the binary search tree formed above. Suppose we have to find node 20 from the
below tree.

Step1:

Step2:

14
Step3:

Now, let's see the algorithm to search an element in the Binary search tree.

Algorithm to search an element in Binary search tree

1. Search (root, item)


2. Step 1 - if (item = root → data) or (root = NULL)
3. return root
4. else if (item < root → data)
5. return Search(root → left, item)
6. else
7. return Search(root → right, item)
8. END if
9. Step 2 - END

15
2. Insertion Operation in BST

In binary search tree, new node is always inserted as a leaf node. The insertion
operation is performed as follows...

• Step 1 - Create a newNode with given value and set


its left and right to NULL.
• Step 2 - Check whether tree is Empty.
• Step 3 - If the tree is Empty, then set root to newNode.
• Step 4 - If the tree is Not Empty, then check whether the value of newNode
is smaller or larger than the node (here it is root node).
• Step 5 - If newNode is smaller than or equal to the node then move to
its left child. If newNode is larger than the node then move to its right child.
• Step 6- Repeat the above steps until we reach to the leaf node (i.e., reaches to
NULL).
• Step 7 - After reaching the leaf node, insert the newNode as left child if the
newNode is smaller or equal to that leaf node or else insert it as right child.

Example 1:

Construct a Binary Search Tree by inserting the following sequence of numbers...

10,12,5,4,20,8,7,15 and 13

Above elements are inserted into a Binary Search Tree as follows...

16
17
Example 2:

A new key in BST is always inserted at the leaf. To insert an element in BST, we
have to start searching from the root node; if the node to be inserted is less than the
root node, then search for an empty location in the left subtree. Else, search for the
empty location in the right subtree and insert the data. Insert in BST is similar to
searching, as we always have to maintain the rule that the left subtree is smaller than
the root, and right subtree is larger than the root.

Now, let's see the process of inserting a node into BST using an example.

18
3. Deletion Operation in BST

In a binary search tree, the deletion operation is performed with O(log n) time
complexity. Deleting a node from Binary search tree includes following three
cases...

• Case 1: Deleting a Leaf node (A node with no children)


• Case 2: Deleting a node with one child
• Case 3: Deleting a node with two children

Case 1: Deleting a leaf node

We use the following steps to delete a leaf node from BST...

• Step 1 - Find the node to be deleted using search operation


• Step 2 - Delete the node using free function (If it is a leaf) and terminate the
function.

When the node to be deleted is the leaf node

• It is the simplest case to delete a node in BST. Here, we have to replace the
leaf node with NULL and simply free the allocated space.
• We can see the process to delete a leaf node from BST in the below image. In
below image, suppose we have to delete node 90, as the node to be deleted is
a leaf node, so it will be replaced with NULL, and the allocated space will
free.

19

Case 2: Deleting a node with one child

We use the following steps to delete a node with one child from BST...

• Step 1 - Find the node to be deleted using search operation


• Step 2 - If it has only one child then create a link between its parent node and
child node.
• Step 3 - Delete the node using free function and terminate the function.

When the node to be deleted has only one child

• In this case, we have to replace the target node with its child, and then delete
the child node. It means that after replacing the target node with its child node,
the child node will now contain the value to be deleted. So, we simply have
to replace the child node with NULL and free up the allocated space.
• We can see the process of deleting a node with one child from BST in the
below image. In the below image, suppose we have to delete the node 79, as
the node to be deleted has only one child, so it will be replaced with its child
55.
• So, the replaced node 79 will now be a leaf node that can be easily deleted.

20

Case 3: Deleting a node with two children

We use the following steps to delete a node with two children from BST...

• Step 1 - Find the node to be deleted using search operation


• Step 2 - If it has two children, then find the largest node in its left
subtree (OR) the smallest node in its right subtree.
• Step 3 - Swap both deleting node and node which is found in the above step.
• Step 4 - Then check whether deleting node came to case 1 or case 2 or else
goto step 2
• Step 5 - If it comes to case 1, then delete using case 1 logic.
• Step 6- If it comes to case 2, then delete using case 2 logic.
• Step 7 - Repeat the same process until the node is deleted from the tree.

When the node to be deleted has two children

This case of deleting a node in BST is a bit complex among other two cases. In such
a case, the steps to be followed are listed as follows -

o First, find the inorder successor of the node to be deleted.

21
o After that, replace that node with the inorder successor until the target node is
placed at the leaf of tree.
o And at last, replace the node with NULL and free up the allocated space.

The inorder successor is required when the right child of the node is not empty. We
can obtain the inorder successor by finding the minimum element in the right child
of the node.

We can see the process of deleting a node with two children from BST in the below
image. In the below image, suppose we have to delete node 45 that is the root node,
as the node to be deleted has two children, so it will be replaced with its inorder
successor. Now, node 45 will be at the leaf of the tree so that it can be deleted easily.

4. Traversal

22
It is a process to visit all the nodes of a tree and may print their values too. Because,
all nodes are connected via edges (links) we always start from the root (head) node.
That is, we cannot randomly access a node in a tree. There are three ways which we
use to traverse a tree −

• In-order Traversal
• Pre-order Traversal
• Post-order Traversal

Generally, we traverse a tree to search or locate a given item or key in the tree or to
print all the values it contains.

1. In-order Traversal

In this traversal method, the left subtree is visited first, then the root and later the
right sub-tree. We should always remember that every node may represent a subtree
itself.

If a binary tree is traversed in-order, the output will produce sorted key values in an
ascending order.

23
We start from A, and following in-order traversal, we move to its left subtree B. B is
also traversed in-order. The process goes on until all the nodes are visited. The output
of inorder traversal of this tree will be −

D→B→E→A→F→C→G

Algorithm
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.

2. Pre-order Traversal

In this traversal method, the root node is visited first, then the left subtree and finally
the right subtree.

We start from A, and following pre-order traversal, we first visit A itself and then
move to its left subtree B. B is also traversed pre-order. The process goes on until
all the nodes are visited. The output of pre-order traversal of this tree will be −

A→B→D→E→C→F→G

24
Algorithm
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree.

3. Post-order Traversal

In this traversal method, the root node is visited last, hence the name. First we
traverse the left subtree, then the right subtree and finally the root node.

We start from A, and following Post-order traversal, we first visit the left
subtree B. B is also traversed post-order. The process goes on until all the nodes are
visited. The output of post-order traversal of this tree will be −

D→E→B→F→G→C→A

Algorithm
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.

25
EXPRESSION TREE
• An expression tree is a special type of binary tree that is used to store
algebraic expressions.

• In an expression tree, each internal node corresponds to the operator and


each leaf node corresponds to the operand.

Consider the algebraic expression given as:

X = (a + b) - (c * d)

This can be represented using a binary tree as follows:

Eg: 4 + ((7 + 9) * 2) will have an expression tree as follows

26
Use of Expression tree

1. The main objective of using the expression trees is to make complex


expressions and can be easily be evaluated using these expression trees.
2. It is also used to find out the associativity of each operator in the expression.
3. It is also used to solve the postfix, prefix, and infix expression evaluation.

Constructing an expression tree

An expression tree can be constructed with the help of a stack. Repeat the
following steps for every character in the postfix expression:

• If the character is an operand, PUSH it on to the stack.


• If the character is an operator, POP two values from the stack and insert them as
the child of operator. A pointer to the new root is pushed on to the stack.
Consider the postfix expression

ab-c*

The following steps are done to create an expression tree.

Since the first two characters are operands, PUSH it onto the stack.

When the - symbol is read, a and b are popped from the stack and is added as the
child of node - .

27
A pointer to the new node is now pushed onto the stack.

Now c is read and is pushed onto the stack.

Finally, the operator * is read, so we pop c and - from the stack and add it as the
child of node * .

When the operation is completed, the pointer to the root of three remains on the
stack.

28
THREADED BINARY TREE

In the linked representation of binary trees, more than one half of the link fields
contain NULL values which results in wastage of storage space. If a binary tree
consists of n nodes then n+1 link fields contain NULL values. Many nodes present
in this tree hold a NULL value in their left or right child pointer (Denoted by
sketched fields). The space occupied by these null values can be used to store some
kind of valuable information.

• One possible way to utilize this space is to have a special pointer that points
to nodes higher in the tree (i.e. ancestors).
• These special pointers are called threads, and the binary tree having such
pointers is called a threaded binary tree.
• A Threaded Binary Tree is a variant of a normal Binary Tree that facilitates
faster tree traversal and does not require a Stack or Recursion. It decreases
the memory wastage by setting the null pointers of a leaf node to the in-
order predecessor or in-order successor
What is a Threaded Binary tree?
• In a Threaded Binary Tree, the nodes will store the in-order
predecessor/successor instead of storing NULL in the left/right child
pointers.
• So the basic idea of a threaded binary tree is that for the nodes whose right
pointer is null, we store the in-order successor of the node (if-exists), and for
the nodes whose left pointer is null, we store the in-order predecessor of the
node(if-exists).

29
• One thing to note is that the leftmost and the rightmost child pointer of a tree
always points to null as their in-order predecessor and successor do not
exist.
Types of Threaded Binary tree
There are two types of Threaded Binary Trees:
• Single-Threaded Binary Tree
• Double-Threaded Binary Tree

• In one-way threaded binary trees, a thread will appear either in the right or left
link field of a node.
• If it appears in the right link field of a node then it will point to the next node
that will appear on performing in order traversal. Such trees are called Right
threaded binary trees.
• If thread appears in the left field of a node then it will point to the nodes
inorder predecessor. Such trees are called Left threaded binary trees.

30
• Left threaded binary trees are used less often as they don't yield the last
advantages of right threaded binary trees.
• In one-way threaded binary trees, the right link field of last node and left link
field of first node contains a NULL.
• In order to distinguish threads from normal links they are represented by
dotted lines.

The above figure shows the inorder traversal of this binary tree yields D, B, E, A, C,
F. When this tree is represented as a right threaded binary tree, the right link field of
leaf node D which contains a NULL value is replaced with a thread that points to
node B which is the inorder successor of a node D. In the same way other nodes
containing values in the right link field will contain NULL value.

31
Two-way threaded Binary Trees:

In two-way threaded Binary trees, the right link field of a node containing NULL
values is replaced by a thread that points to nodes inorder successor and left field of
a node containing NULL values is replaced by a thread that points to nodes inorder
predecessor.

The above figure shows the inorder traversal of this binary tree yields D, B, E, G, A,
C, F. If we consider the two-way threaded Binary tree, the node E whose left field
contains NULL is replaced by a thread pointing to its inorder predecessor i.e. node

32
B. Similarly, for node G whose right and left linked fields contain NULL values are
replaced by threads such that right link field points to its inorder successor and left
link field points to its inorder predecessor. In the same way, other nodes containing
NULL values in their link fields are filled with threads.

• In the above figure of two-way threaded Binary tree, we noticed that no left
thread is possible for the first node and no right thread is possible for the last
node.
• This is because they don't have any inorder predecessor and successor
respectively. This is indicated by threads pointing nowhere. So in order to
maintain the uniformity of threads, we maintain a special node called
the header node.
• The header node does not contain any data part and its left link field points
to the root node and its right link field points to itself.
• If this header node is included in the two-way threaded Binary tree then this
node becomes the inorder predecessor of the first node and inorder successor
of the last node.
• Now threads of left link fields of the first node and right link fields of the
last node will point to the header node.

33

You might also like