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

Chapter 4 Tree and Graph

Chapter 4 discusses trees and graphs, focusing on tree structures as non-linear data types that simulate hierarchies and their various terminologies. It covers binary trees, their types, operations, and traversal methods, as well as the representation and traversal of graphs using Depth First Search (DFS) and Breadth First Search (BFS) algorithms. The chapter provides algorithms for creating, inserting, deleting, and searching within binary search trees.

Uploaded by

prashantkori
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Chapter 4 Tree and Graph

Chapter 4 discusses trees and graphs, focusing on tree structures as non-linear data types that simulate hierarchies and their various terminologies. It covers binary trees, their types, operations, and traversal methods, as well as the representation and traversal of graphs using Depth First Search (DFS) and Breadth First Search (BFS) algorithms. The chapter provides algorithms for creating, inserting, deleting, and searching within binary search trees.

Uploaded by

prashantkori
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

CHAPTER 4:- TREE AND GRAPH

Introduction to Tree:
● Tree is a non-linear data structure, non-linear data structures are capable of
expressing more complex relationship than linear data structure
● A tree is a widely used Abstract Data Type(ADT) that simulates a hierarchical
tree structure.
● A tree is used for improving database search engine time, game programming,
3D graphics, data compression and in files system.
● Let us see some example,
Princip
al

Physic
CS HOD HOD

FY Class SY class FY Class SY class


Teacher Teacher Teacher Teacher
Definition of Tree
❖ Tree can be defined as a collection of entities(nodes) linked
together to simulate a hierarchy.
Tree Terminology

❖ Leaf Node: The node which does not have a child is called as
leaf node.
❖ Degree of a node: The total number of children of a node is
called as degree of a node.
❖ Degree of a tree: The highest degree of node among all the
nodes in a tree is called as degree of a tree.
❖ Level of Node: In a tree each step from top to bottom is called as
a level of node. level count starts from 0 and incremented by
one at each level.
❖ Height: The total number of edges from leaf node to a particular
node in the longest path is called as HEIGHT of that node.
❖ Depth: The total number edges from root node to a particular
node is called DEPTH of that node.
Tree Terminology
❖ Null tree: A tree with no nodes is a null tree.
❖ Node: Every individual element is called as Node.
❖ Root Node: a root node is special node which doesn’t have
parent node.
❖ Parent Node: The node which has a branch from it to any other
node is called a parent node.
❖ Child Node: The node which has a link from its parent node is
called as child node.
❖ Siblings: The nodes with same parent are called siblings.
BINARY TREE AND IT’ S TYPES
Binary Tree: It is a tree where every node can have at the most two
branches(children).

Strictly Binary Tree: A strictly binary tree is a binary tree where all
non-leaf node have two branches.
1. Complete Binary Tree: In a complete binary tree all level
accept the last are completely filled.

2. Full Binary Tree: in this tree all node have either zero or two
child nodes.
Perfect Binary Tree: in which all internal nodes have two children
and all leaves at same level.

Skewed Binary Tree: A tree in which every node have only left
subtree or right subtree is called as skewed binary tree.
Rooted Tree: In rooted tree every edge directly or indirectly
originate from the root.

Binary Search Tree: all nodes in the left subtree have values less
than the root and the node in the right sub tree have values greater
than the root.
Represenation of Binary Tree:
1. Sequential representation using array
2. Linked representation.
1.Sequential representation using array:
2. . Linked representation of Tree.
• All nodes should be allow dynamically.
• The fundamental component of binary tree is node.
• Each node consist of three field, Lchild, Data, Rchild.
Node

Lchild Data Rchild

Data

Lchild Rchild
Node

Lchild Data Rchild

• The Lchild field holds the address of its left node and Rchild field
holds the address of right node.
Node

Lchild Data Rchild

struct Node {
int data;
Node *left, *right;
};

// Function to create a new node


Node* createNode(int key) {
Node* newNode =(Node*) malloc(sizeof( Node));
newNode->data = key;
newNode->left = newNode->right = NULL;
return newNode;
}
Operations on Binary Trees:
1. Create: creating a tree
2. Traversal: to visit all the nodes in a binary tree.
⚫ Preorder
⚫ Inorder
⚫ Postorder
3. Insertion : to insert a node in the binary tree.
4. Delete: to delete a node from the binary tree.
5. Search a key: search an element from tree.
BINARY SEARCH TREE(BST)
● Binary Search Tree: all nodes in the left subtree have values
less than the root and the node in the right subtree have
values greater than the root.

Example(CW): Construct Binary Tree on the given data


Heena,Deepa,Teena,Meena,Beena,Anita
Creating Binary Search Tree
❏ The function create() simply creates a empty binary search tree. this
initializes the root pointer to NULL.
struct tree *root=NULL;
Algorithm:
1: root=NULL
2: read key and create a new node to store key value
3: if root is NULL then new node is root.
4: t=root
5: while(t!=null)
case 1:if key < t -> data attach new node to t -> left
case 2: if key > t -> data attach new node to t -> right
case 3: if t -> data = key then print “key already exists”.
6: stop.
The Non Recursive Function inserting node into BST:
void insertNode(Node* &root, int key) {
Node* newNode = createNode(key); if (key < parent->data) {
if (root == NULL) { parent->left = newNode;
root = newNode; } else {
return; parent->right = newNode;
} }
Node* t = root; }
Node* parent = NULL;
while (t != NULL) {
parent = t;
if (key < t->data) {
t = t->left;
} else if (key > t->data) {
t = t->right;
} else {
cout << "Key " << key << " already exists.\n";
free(newNode);
return;
}
}
The Recursive Function inserting node into BST:

Node* insertNodeRecursive(Node* root, int key) {


if (root == NULL) {
return createNode(key);
}

if (key < root->data) {


root->left = insertNodeRecursive(root->left, key);
} else if (key > root->data) {
root->right = insertNodeRecursive(root->right, key);
} else {
cout << "Key " << key << " already exists.\n";
}

return root;
}
Binary Tree Traversal:
• When we want to display a binary tree, we need to follow
some order in which all the node of that binary tree must be
displayed.
• In binary tree displaying order of nodes depends on the
traversal method.
Methods of Traversing Tree:
1. Preorder traversal
2. Inorder traversal
3. Postorder traversal

1.Preorder traversal (DLR)


In this traversal root node is visited first, then its left child and later its right child.
• Process the root Data(D)
• Traverse the left subtree of D in preorder (Left-L)
• Traverse the Right subtree of D in preorder (Right-R).
Algorithm for Preorder Traversal of a Binary Tree
1. Start
2. If the root is NULL, return (base case for recursion).
3. Visit the current node (process or print its data).
4. Recursively traverse the left subtree.
5. Recursively traverse the right subtree.
6. End
The Recursive Function for preorder traversal of BST:

void preorderTraversal(Node* root) {


if (root == NULL) {
return;
}
cout << root->data << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
2.Inorder Traversal (LDR)
In this traversal, left child node is visited first, then the root node
is visited and later right child node will be visited.
• Traverse the left subtree of D in preorder (Left-L)
• Process the root Data(D)
• Traverse the Right subtree of D in preorder (Right-R).
Recursive Inorder traversal:
Step 1: begin
Step 2: if tree is not empty
inorder(left child)
visit the root
inorder(right child)
Step 3: end
Recursive function for Inorder Traversal (LDR)
void inorderTraversal(Node* root) {
if (root == NULL) {
return;
}

inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
3.Postorder Traversal (LRD)
In this traversal left child node is visited fist, then its right child
and then its root node.
• Traverse the left subtree of D in preorder (Left-L)
• Traverse the Right subtree of D in preorder (Right-R).
• Process the root Data(D)

Recursive post traversal:


Step 1: begin
Step 2: if tree is not empty
postorder(left child)
postorder(right child)
visit the root
Step 3: end
Recursive function for Postorder Traversal (LRD)
void post(Node* root) {
if (root == NULL) {
return;
}
post(root->left);
post(root->right);
cout << root->data << " ";
}
Delete a Node from BST
Case 1: if the node to be deleted is leaf node, then we only replace the
link to the deleted node null.
Delete a Node from BST
Case 2: if the node to be deleted has single child node,Copy the child to
the parent node and delete the node.
Delete a Node from BST
Case 3: The node to be deleted having both child nodes.The trick is to
find the inorder successor of the node. Copy contents of the inorder
successor to the node, and delete the inorder successor.

or :Attach the right subtree in place of the deleted node and then attach
the left subtree to the appropriate node of right subtree.
function to Delete a Node from BST // If root matches with the given key
Node* getSuccessor(Node* curr){ else {
curr = curr->right; // Cases when root has 0 children
while (curr != NULL && curr->left ! // or only right child
=NULL) if (root->left ==NULL) {
curr = curr->left; Node* temp = root->right;
return curr; delete root;
} return temp;
}
Node* delNode(Node* root, int x){ // When root has only left child
if (root->right ==NULL) {
// Base case Node* temp =root->left;
if (root == NULL)
delete root;
return root;
return temp;
// If key to be searched is in a subtree }
if (root->key > x) // When both children are present
root->left = delNode(root->left, x); Node* succ = getSuccessor(root);
else if (root->key < x) root->key = succ->key;
root->right = delNode(root->right, x); root->right = delNode(root->right, succ->key);
}
return root;
}
Searching in a BST
● To search a target key,we first compare it with the key at the
root of the tree. if it is same, then the search ends and if it is
less than key at root, search the target key in left subtree else
search in the right subtree.
The Non Recursive Function for search Key: Recursive Function for search Key:
node *search(node *root, int Key) node *rsearch(node *root, int Key)
{ {
node *temp=root; node *temp=root;
while(temp!=NULL) && (temp -> data != NULL) if (temp = = NULL) | | (temp -> data = = key)
{ return temp;
if(key==temp->data) else
{ if(key < temp -> data)
return temp; research(temp -> left, key);
} else
else if(key < temp -> data) research(temp -> right, key);
temp= temp -> left; }
else
temp= temp -> right;
}
return(temp);
}
GRAPH
Representation of Graph
1. Sequential representation(Adjacency matrix) using array
2. Linked representation(Adjacency list) using linked list.
1. Sequential representation(Adjacency matrix)
An adjacency matrix is a way of representing a graph as a matrix of boolean (0’s and 1’s).
Graph Traversal
●The process of visiting and exploring a graph for processing is called traversal.
1. Depth First Search(DFS)
2. Breadth First Search(BFS)

1. Depth First Search(DFS) It uses a Stack


● The depth-first search (DFS) algorithm starts with the initial node of graph
G and goes deeper until we find the goal node or the node with no children.
● It is a recursive algorithm to search all the vertices of a tree data structure or
a graph.
The step by step process to implement the DFS traversal is given as follows -
1. First, create a stack with the total number of vertices in the graph.
2. Now, choose any vertex as the starting point of traversal, and push that
vertex into the stack.
3. After that, push a non-visited vertex (adjacent to the vertex on the top of the
stack) to the top of the stack.
4. Now, repeat steps 3 and 4 until no vertices are left to visit from the vertex
on the stack's top.
5. If no vertex is left, go back and pop a vertex from the stack.
6. Repeat steps 2, 3, and 4 until the stack is empty.
Algorithm using stack for DFS
Step 1: Push start vertex onto STACK.
Step 2: while(not empty(stack)) do
begin
v= POP(stack)
if (not visited (v))
begin
visited[v]=1
push all adjacent vertices of v onto stack
end
end
step 3: stop
2. Breadth First Search(BFS) It uses a Queue
● Breadth-first search is a graph traversal algorithm that starts traversing the
graph from the root node and explores all the neighboring nodes.
● It selects the nearest node and explores all the unexplored nodes. While
using BFS for traversal, any node in the graph can be considered as the root
node.
The step by step process to implement the BFS traversal is given as follows -
1. Start by selecting a starting vertex or node.
2. Add the starting vertex to the end of the queue.
3. Mark the starting vertex as visited and add it to the visited array/list.
4. While the queue is not empty, do the following steps:
a. Remove the front vertex from the queue.
b. Visit the removed vertex and process it.
c. Enqueue all the adjacent vertices of the removed vertex that have not
been visited yet.
d. Mark each visited adjacent vertex as visited and add it to the visited
array/list.
5. Repeat step 4 until the queue is empty.
Algorithm using stack for BFS
Step 1: Add start vertex onto QUEUE.
Step 2: while(not empty(QUEUE)) do
begin
i= delete(QUEUE)
for all vertices j adjacent to i do
begin
if ( not visited[j] = = 1)
add (QUEUE, j)
visited[j]=1
end
end
step 3: stop

You might also like