0% found this document useful (0 votes)
18 views60 pages

DS Unit 4

Unit 4 of the Data Structures using C++ course focuses on Trees and Graphs, covering topics such as tree terminology, binary trees, binary search trees, AVL trees, and graph representation methods. It includes detailed explanations of tree operations, traversal techniques, and various types of binary trees, along with their applications in computer science. The unit also discusses algorithms for tree traversal and the complexities involved in these operations.

Uploaded by

evan.mathew
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)
18 views60 pages

DS Unit 4

Unit 4 of the Data Structures using C++ course focuses on Trees and Graphs, covering topics such as tree terminology, binary trees, binary search trees, AVL trees, and graph representation methods. It includes detailed explanations of tree operations, traversal techniques, and various types of binary trees, along with their applications in computer science. The unit also discusses algorithms for tree traversal and the complexities involved in these operations.

Uploaded by

evan.mathew
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/ 60

Data Structures using C++

Unit 4

MISSION VISION CORE VALUES


CHRIST is a nurturing ground for an individual’s Excellence and Service Faith in God | Moral Uprightness
holistic development to make effective contribution to Love of Fellow Beings
the society in a dynamic environment Social Responsibility | Pursuit of Excellence
CHRIST
Deemed to be University

Unit 4 Topics

TREES & GRAPHS


● Trees: Introduction, Terminology, Representation of Trees, Binary Trees, The
Abstract Data Type, Properties of Binary Tress, Binary Tree Representations, Binary
Tree Traversal and Tree Iterators, Introduction, Inorder Traversal, Preorder Traversal,
Postorder Traversal.
● Binary Search Trees, Definition, ADT, Implementation, Operations‐ Searching,
Insertion and Deletion, AVL Trees, Definition, Height of an AVL Tree, Operations –
Insertion, Deletion and Searching.
● Graphs: Basic terminology, representation of graphs, graph search methods DFS,
BFS.

Excellence and Service


CHRIST
Deemed to be University

Trees: Introduction

● A tree data structure is a hierarchical structure that is used to


represent and organize data in a way that is easy to navigate
and search.
● It is a collection of nodes that are connected by edges and has
a hierarchical relationship between the nodes.

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Trees can be represented in two ways as listed below:

1. Dynamic Node Representation (Linked Representation).


2. Array Representation (Sequential Representation).

Excellence and Service


CHRIST
Deemed to be University

Basic Terminologies In Tree Data Structure:


• Parent Node: The node which is a predecessor of a node is
called the parent node of that node. {B} is the parent node
of {D, E}.
• Child Node: The node which is the immediate successor of a
node is called the child node of that node. Examples: {D, E} are
the child nodes of {B}.
• Root Node: The topmost node of a tree or the node which
does not have any parent node is called the root node. {A} is
the root node of the tree. A non-empty tree must contain
exactly one root node and exactly one path from the root to all
other nodes of the tree.
• Leaf Node or External Node: The nodes which do not have
any child nodes are called leaf nodes. {K, L, M, N, O, P, G} are
the leaf nodes of the tree.

Excellence and Service


CHRIST
Deemed to be University

• Ancestor of a Node: Any predecessor nodes on the path of the


root to that node are called Ancestors of that node. {A,B} are
the ancestor nodes of the node {E}
• Descendant: A node x is a descendant of another node y if and
only if y is an ancestor of y.
• Sibling: Children of the same parent node are called
siblings. {D,E} are called siblings.
• Level of a node: The count of edges on the path from the root
node to that node. The root node has level 0.
• Internal node: A node with at least one child is called Internal
Node.
• Neighbour of a Node: Parent or child nodes of that node are
called neighbors of that node.
• Subtree: Any node of the tree along with its descendant.

Excellence and Service


CHRIST
Deemed to be University

Types of Tree data structures:

Excellence and Service


CHRIST
Deemed to be University

Basic Operation Of Tree Data Structure

• Create – create a tree in the data structure.


• Insert − Inserts data in a tree.
• Search − Searches specific data in a tree to check whether it is
present or not.
• Traversal:
• Preorder Traversal – perform Traveling a tree in a pre-order manner in the
data structure.
• In order Traversal – perform Traveling a tree in an in-order manner.
• Post-order Traversal –perform Traveling a tree in a post-order manner.

Excellence and Service


CHRIST
Deemed to be University

Binary Trees

● The Abstract Data Type

Excellence and Service


CHRIST
Deemed to be University

Binary Tree

● A binary tree is defined as a tree in which no node can


have more than two children. The highest degree of
any node is two. This indicates that the degree of a
binary tree is either zero or one or two

Excellence and Service


CHRIST
Deemed to be University

Properties of Binary Trees

The following are some of the important properties of a binary


tree:
• A binary tree allows for a maximum of two children per node.
• The maximum number of edges between the root and a leaf
node determines the height of a binary tree.
• A binary tree can have a maximum of 2d nodes at depth d.
• A binary tree of height h can have a maximum of 2(h+1) –
1 nodes.
• In a binary tree, there can only be as many leaf nodes as
internal nodes plus one.

Excellence and Service


CHRIST
Deemed to be University

Binary Tree Representations

A binary tree data structure is represented using two methods:

1. Array Representation
2. Linked List Representation

Array Representation

Excellence and Service


CHRIST
Deemed to be University

Linked List Representation

Excellence and Service


CHRIST
Deemed to be University

Use any below method to implement Nodes of tree


Method 1: Using "struct" to make user-defined data type
struct node {
int data;
struct node* left;
struct node* right;
};

Method 2: Using "class" to make user-defined data type


class Node {
public:
int data;
Node* left;
Node* right;
};

Excellence and Service


CHRIST
Deemed to be University

Types of Binary Trees

There are several types of binary trees based on their properties-


● Binary Tree based on the number of children:
• Full Binary Tree
• Degenerate Binary Tree
• Skewed binary tree

● Binary Tree based on the completion of levels:


• Complete binary tree
• Balanced binary tree
• Perfect binary tree

Excellence and Service


CHRIST
Deemed to be University

● A Binary Tree is a full binary tree if every node has 0 or 2


children.

Excellence and Service


CHRIST
Deemed to be University

● A Degenerate (or pathological) tree is a tree where every


internal node has one child. Such trees are performance-wise
same as linked list. A degenerate or pathological tree is a tree
having a single child either left or right.
● Max nodes: h+1

Excellence and Service


CHRIST
Deemed to be University

● A skewed binary tree is a pathological/degenerate tree in


which the tree is either dominated by the left nodes or the
right nodes.
● Max nodes: h+1

Excellence and Service


CHRIST
Deemed to be University

● A complete binary tree is just like a full binary tree, but with
two major differences:
• Every level except the last level must be completely filled.
• All the leaf elements must lean towards the left.
• 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.

Excellence and Service


CHRIST
Deemed to be University

● A Binary tree is a Perfect Binary Tree in which all the internal


nodes have two children and all leaf nodes are at the same
level.
● Max nodes: 2h+1 – 1

Excellence and Service


CHRIST
Deemed to be University

● A Balanced Binary Tree 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.

Excellence and Service


CHRIST
Deemed to be University

Applications of Binary Trees


Binary trees have a wide range of applications in computer science and other
fields:
• Expression evaluation: In order to evaluate arithmetic expressions, binary
trees are used.
• Data compression: The widely used data compression method known as
Huffman coding uses binary trees to describe the frequency of characters
in a message.
• Decision-making processes: Binary trees may be utilized in
decision-making procedures such as game trees and decision trees.
• Network routing: To effectively route packets via a network, network
routing methods use binary trees for the transfer of packet.
• Machine learning: Binary trees are utilized in machine learning
techniques like decision trees and random forests to model and classify
the data.

Excellence and Service


CHRIST
Deemed to be University

Tree Traversal Techniques

● Unlike linear data structures (Array, Linked List, Queues,


Stacks, etc) which have only one logical way to traverse them,
trees can be traversed in different ways:

1. Depth First Search or DFS


1. Inorder Traversal
2. Preorder Traversal
3. Postorder Traversal
2. Level Order Traversal or Breadth First Search or BFS
3. Boundary Traversal
4. Diagonal Traversal

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

● InOrder: (left,root, right): 25,12,30,19,36,15


● PreOrder: (root,left,right): 10,12,25,30,15,36
● PostOrder: (left,right,root):25,30,12,36,15,10

Excellence and Service


CHRIST
Deemed to be University

Inorder Traversal of Binary Tree

Inorder traversal is defined as a type of tree traversal


technique which follows the Left-Root-Right pattern, such that:
• The left subtree is traversed first
• Then the root node for that subtree is traversed
• Finally, the right subtree is traversed

Excellence and Service


CHRIST
Deemed to be University

Algorithm for Inorder Traversal of Binary Tree


Algorithm Inorder(tree)

1. Traverse the left subtree, i.e., call Inorder(left->subtree)


2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right->subtree)

Excellence and Service


CHRIST
Deemed to be University

Algorithm for Preorder Traversal of Binary Tree

Algorithm Preorder(tree)

1. Visit the root.


2. Traverse the left subtree, i.e., call Preorder(left->subtree)
3. Traverse the right subtree, i.e., call Preorder(right->subtree)

Excellence and Service


CHRIST
Deemed to be University

Algorithm for Postorder Traversal of Binary Tree

Algorithm Postorder(tree)

1. Traverse the left subtree, i.e., call Postorder(left->subtree)


2. Traverse the right subtree, i.e., call Postorder(right->subtree)
3. Visit the root

Excellence and Service


CHRIST
Deemed to be University

Construct Binary Tree from Inorder and Postorder Traversal

Algorithm: buildTree()
1. Pick an element from Preorder. Increment a Preorder Index
Variable (preIndex in below code) to pick the next element in
the next recursive call.
2. Create a new tree node tNode with the data as the picked
element.
3. Find the picked element’s index in Inorder. Let the index be
inIndex.
4. Call buildTree for elements before inIndex and make the built
tree as a left subtree of tNode.
5. Call buildTree for elements after inIndex and make the built
tree as a right subtree of tNode.
6. return tNode.

Excellence and Service


CHRIST
Deemed to be University

Complexity Analysis
Time Complexity Analysis:
● In general, if we want to analyze the time complexity of a tree
traversal then we have to think in terms of the number of nodes
visited.
● Hence, if a tree has n nodes, then each node is visited only
once in traversal (inorder, preorder and postorder) and
hence the complexity of the inorder traversal of the binary tree
is O(n) .
Space Complexity Analysis:
● For a tree of height h, space complexity is O(h) since space
complexity of recursion is always the height / depth of
recursion.
● For skewed trees, the height of the tree may be equal to the
number of nodes in the tree, hence leading to an overall space
complexity of O(n)
Excellence and Service
CHRIST
Deemed to be University

Binary Search Tree

● A Binary Search Tree is a data structure used in computer


science 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.

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

BST: Search operation

1. First, compare the element to be searched with the root


element of the tree.
2. If root is matched with the target element, then return the
node's location.
3. If it is not matched, then check whether the item is less
than the root element, if it is smaller than the root element,
then move to the left subtree.
4. If it is larger than the root element, then move to the right
subtree.
5. Repeat the above procedure recursively until the match is
found.
6. If the element is not found or not present in the tree, then
return NULL.

Excellence and Service


CHRIST
Deemed to be University

BST: Deletion Operation

In a binary search tree, we must delete a node from the tree


by keeping in mind that the property of BST is not violated. To
delete a node from BST, there are three possible situations
occur -
• The node to be deleted is the leaf node, or,
• The node to be deleted has only one child, and,
• The node to be deleted has two children

Excellence and Service


CHRIST
Deemed to be University

Delete 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.

Excellence and Service


CHRIST
Deemed to be University

Delete node that 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.

Excellence and Service


CHRIST
Deemed to be University

Delete a node that 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 -
• First, find the inorder predecessor/successor of the node to be
deleted.
• After that, replace that node with the inorder predecessor/successor
until the target node is placed at the leaf of tree.
• And at last, replace the node with NULL and free up the allocated
space.
Note: We can obtain the inorder successor by finding the minimum
element in the right child of the node and the inorder predecessor by
finding the maximum element in the left child.

Excellence and Service


CHRIST
Deemed to be University

BST: Insertion operation

● 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.

Excellence and Service


CHRIST
Deemed to be University

AVL Tree

● An AVL tree is defined as a self-balancing Binary Search Tree


(BST) where the difference between heights of left and right
subtrees for any node cannot be more than one.
● It is also known as Adelson-Velsky and Landis tree

● Each node is associated with a balance factor which is


calculated by subtracting the height of its right sub-tree from
that of its left sub-tree.

● Tree is said to be balanced if balance factor of each node is in


between -1 to 1, otherwise, the tree will be unbalanced and
need to be balanced.
● Balance Factor (k) = height (left(k)) - height (right(k))

Excellence and Service


CHRIST
Deemed to be University

AVL tree
● If balance factor of any node is 1,
it means that the left sub-tree is
one level higher than the right
sub-tree.
● If balance factor of any node is 0,
it means that the left sub-tree
and right sub-tree contain equal
height.
● If balance factor of any node is
1, it means that the left sub-tree
is one level lower than the right
sub-tree.
● An AVL tree is given in the given
figure. We can see that, balance
factor associated with each node
is in between 1 Excellence
and and1.Service
CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Graphs: Basic terminology


● Vertices & Edges
● Directed: initial node to terminal node
● Undirected
● Path: Sequence of nodes followed to reach TN from IN
● Closed Path: If TN=IN
● Cycle: No repeated edges or vertices except first and las vertices
● Connected graph: Some path exists between every 2 vertices. No ISOLATED
nodes

● Complete graph: Every node connected to all other nodes. Edges: n(n-1)/2
● Weighted graph: Assigned some value for cost of travelling edge
● Adjacent nodes: Nodes connected via an edge
Excellence and Service
CHRIST
Deemed to be University

Graph Representation: Sequential


Adjacency Matrix: An adjacency matrix is a way of representing a graph as a
matrix of boolean (0’s and 1’s).
• If there is an edge from vertex i to j, mark adjMat[i][j] as 1.
• If there is no edge from vertex i to j, mark adjMat[i][j] as 0.
• If weighted the adjMat[i][j] =weight of edge

Excellence and Service


CHRIST
Deemed to be University

● Adjacency Matrix for Weighted graph

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Graph Representation: Linked List


Adjacency List: An adjacency list is used in the linked representation to
store the Graph in the computer's memory. It is efficient in terms of storage
as we only have to store the values for edges.
○ Undirected: Sum of lengths of adjacency list equal to twice the
number of edges present
○ Directed: Sum of lengths=No of edges
○ Weighted: An extra field is added.

Excellence and Service


CHRIST
Deemed to be University

● Adjacency List for Directed Graph

Excellence and Service


CHRIST
Deemed to be University

Adjacency List for Weighted Graph

Excellence and Service


CHRIST
Deemed to be University

Breadth First Search or BFS for a Graph


Breadth First Search (BFS) is a fundamental graph traversal algorithm. It involves
visiting all the connected nodes of a graph in a level-by-level manner.
○ Start from root node
○ Explore neighbouring nodes
○ Select new node, explore all unexplored nodes
○ Use Queue
○ To avoid processing same node, Keep track of visited and unvisited nodes

Excellence and Service


CHRIST
Deemed to be University

Algorithm for BFS:

1. Initialization: Enqueue the starting node into a queue and


mark it as visited.
2. Exploration: While the queue is not empty:
2. Dequeue a node from the queue and visit it (e.g., print its value).
3. For each unvisited neighbor of the dequeued node:
2. Enqueue the neighbor into the queue.
3. Mark the neighbor as visited.
3. Termination: Repeat step 2 until the queue is empty.

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

● Now, Queue becomes empty, So, terminate these process of


iteration.

Excellence and Service


CHRIST
Deemed to be University

Depth First Search or DFS for a Graph

● Depth First Traversal (or DFS) for a graph is similar to Depth


First Traversal of a tree.
● The only catch here is, that, unlike trees, graphs may contain
cycles (a node may be visited twice). To avoid processing a
node more than once, use a boolean visited array. A graph can
have more than one DFS traversal.

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Now, Stack becomes empty, which means we have visited all the
nodes and our DFS traversal ends
Excellence and Service

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy