Unit 4: Trees
Unit 4: Trees
Unit 4: Trees
1. Consider the algebraic expression given as: Exp = (a – b) + (c * d) and represent it using a binary tree.
2. Given an expression, Exp = ((a + b) – (c * d)) % ((e ^f) / (g – h)), construct the corresponding binary
tree.
3.Given the binary tree, write down the expression that it represents
4.Expression for the above binary tree is[{(a/b) + (c*d)} ^ {(f % g)/(h – i)}]
5.For a following binary tree find the sequence of nodes that will be visited using thepreorder, in
order, post order and level order.
OR
6.For a following binary tree find the sequence of nodes that will be visited using thepreorder, in
order, post order and level order.
7.For the following binary tree find the internal and external path length.
Solution
Weighted external path length of T1 can be given as,
P1 = 2*3 + 3*3 + 5*2 + 11*3 + 5*3 + 2*2 = 6 + 9 + 10 + 33 + 15 + 4 = 77
Weighted external path length of T2 can be given as,
P2 = 5*2 + 7*2 + 3*3 + 4*3 + 2*2 = 10 + 14 + 9 + 12 + 4 = 49
Weighted external path length of T3 can be given as,
P3 = 2*3 + 3*3 + 5*2 + 11*1 = 6 + 9 + 10 + 11 = 36
9.Create a Huffman tree with the following nodes arranged in a priority queue.
10.In the Huffman tree, circles contain the cumulative weights of their child nodes. Every left branch is
coded with 0 and every right branch is coded with 1. Write the codes for the characters A, E, R, W, X, Y,
and Z.
11.State the applications of trees.
Σ Trees are used to store simple as well as complex data. Here simple means an integer value,
character value and complex data means a structure or a record.
Σ Trees are often used for implementing other types of data structures like hash tables, sets, and
maps.
Σ A self-balancing tree, Red-black tree is used in kernel scheduling, to preempt massively
multiprocessor computer operating system use. (We will study red-black trees in next chapter.)
Σ Another variation of tree, B-trees are prominently used to store tree structures on disc. They
are used to index a large number of records.
Σ B-trees are also used for secondary indexes in databases, where the index facilitates a select
operation to answer some range criteria.
Σ Trees are an important data structure used for compiler construction.
Σ Trees are also used in database design.
Σ Trees are used in file system directories.
Σ Trees are also widely used for information storage and retrieval in symbol tables.
A binary search tree, also known as an ordered binary tree, is a variant of binary trees in whichthe
nodes are arranged in an order.
In a binary search tree, all the nodes in the left sub-tree have a value less than that of the root node.
Correspondingly, all the nodes in the right sub-tree have a value either equal to or greater than the root
node. The same rule is applicable to every sub-tree in the tree.
Ex.
13.Create a binary search tree using the following data elements: 45, 39, 56, 12, 34, 78, 32,10, 89, 54,
67, 81
14.Consider the following binary tree and insert 12 and 55 into it.
Unit 5: Graphs
1. Explain the concept of Graph. Why Graphs are useful? And Define the Graph.
A graph is an abstract data structure that is used to implement the mathematical concept of graphs.
It is basically a collection of vertices (also called nodes) and edges that connect these vertices. A
graph is often viewed as a generalization of the tree structure, where instead of having a purely
parent-to-child relationship between tree nodes, any kind of complex relationship can exist.
Why are Graphs Useful?
Graphs are widely used to model any situation where entities or things are related to each other in
pairs. For example, the following information can be represented by graphs:
Σ Family trees in which the member nodes have an edge from parent to each of their children.
Σ Transportation networks in which nodes are airports, intersections, ports, etc. The edges can be
airline flights, one-way roads, shipping routes, etc.
Definition
A graph G is defined as an ordered set (V, E), where V(G) represents the set of vertices and E(G)
represents the edges that connect these vertices.
2.Define the graph terminologies adjacent nodes, degree of a node, regular graph, path,connected
graph and complete graph.
Graph Terminology
Adjacent nodes or neighbours -For every edge, e = (u, v) that connects nodes u and v, the nodes
u and v are the end-points and are said to be the adjacent nodes or neighbours.
Degree of a node -Degree of a node u, deg(u), is the total number of edges containing the node
u.
Regular graph -It is a graph where each vertex has the same number of neighbours. That is, every
node has the same degree. A regular graph with vertices of degree k is called a k–regular graph or
a regular graph of degree k.
Path -A path P written as P = {v0, v1, v2, ..., vn), of length n from a node u to v is defined as a
sequence of (n+1) nodes.
Connected graph -A graph is said to be connected if for any two vertices (u, v) in V there is a
path from u to v. That is to say that there are no isolated nodes in a connected graph. A connected
graph that does not have any cycle is called a tree. Therefore, a tree is treated as a special graph
Complete graph -A graph G is said to be complete if all its nodes are fully connected. That is,
there is a path from one node to every other node in the graph. A complete graph has n(n–1)/2
edges, where n is the number of nodes in G.
3.Define pendent vertex, isolated vertex, cut vertex, sink, source, reachability and stronglyconnected
graph.
Isolated vertex -A vertex with degree zero. Such a vertex is not an end-point of any edge.
Pendant vertex (also known as leaf vertex) -A vertex with degree one.
Cut vertex -A vertex which when deleted would disconnect the remaining graph.
Source -A node u is known as a source if it has a positive out-degree but a zero in-degree.
Sink -A node u is known as a sink if it has a positive in-degree but a zero out-degree.
Reachability -A node v is said to be reachable from node u, if and only if there exists a (directed)
path from node u to node v. For example, if you consider the directed graph given in Fig. below(a),
you will observe that node D is reachable from node A.
Strongly connected directed graph -A digraph is said to be strongly connected if and only if
there exists a path between every pair of nodes in G. That is, if there is a path from node u to v,
then there must be a path from node v to u.
5.Show the adjacency matrix representation of following directed graph with loop.
OR
11.Show the adjacency list representation of following weighted graph.
The depth-first search algorithm (Fig. below) progresses by expanding the starting node of G and
then going deeper and deeper until the goal node is found, or until a node that has no children is
encountered. When a dead-end is reached, the algorithm backtracks, returning to the most recent
node that has not been completely explored.
In other words, depth-first search begins at a starting node A which becomes the current node. Then, it examines
each node N along a path P which begins at A. That is, we process a neighbor of A, then a neighbour of neighbour
of A, and so on. During the execution of the algorithm, if wereach a path that has a node N that has already been
processed, then we backtrack to the current node. Otherwise, the unvisited (unprocessed) node becomes the
current node.
15.Consider the graph G given in Fig. below. The adjacency list of G is also given. Assume that G represents the daily
flights between different cities and we want to fly from city A to I with minimum stops. That is, find the minimum
path P from A to I given that every edge has a length of 1 using BFS.
16.Consider DAGs shown in Fig. below and their possible topological sorts.
OR
17.Consider DAGs shown in Fig. below and their possible topological sorts.
OR
18. Consider DAGs shown in Fig. below and their possible topological sorts.
ANS:
18.Write the algorithm for topological sort and explain it.
The algorithm for the topological sort of a graph (Fig. below) that has no cycles focuses on
selecting a node N with zero in-degree, that is, a node that has no predecessor. The two main steps
involved in the topological sort algorithm include:
Σ Selecting a node with zero in-degree
Σ Deleting N from the graph along with its edges
19.Consider a directed acyclic graph G given in Fig. Use the topological algorithm to find atopological
sort T of G.
20.State the concept of minimum spanning tree and discuss its properties.
A spanning tree of a connected, undirected graph G is a sub-graph of G which is a tree that connects all the vertices
together. A graph G can have many different spanning trees. We can assign weights to each edge (which is a number
that represents how unfavourable the edge is), and use it to assign a weight to a spanning tree by calculating the sum
of the weights of the edgesin that spanning tree. A minimum spanning tree (MST) is defined as a spanning tree with
weight less than or equal to the weight of every other spanning tree. In other words, a minimum spanning tree is a
spanning tree that has weights associated with its edges, and the total weight ofthe tree (the sum of the weights of its
edges) is at a minimum.
Properties
Possible multiplicity -There can be multiple minimum spanning trees of the same weight.Particularly, if all
the weights are the same, then every spanning tree will be minimum.
Uniqueness -When each edge in the graph is assigned a different weight, then there will be onlyone unique
minimum spanning tree.
Minimum-cost subgraph -If the edges of a graph are assigned non-negative weights, then aminimum spanning tree is in
fact the minimum-cost subgraph or a tree that connects all vertices.
Cycle property -If there exists a cycle C in the graph G that has a weight larger than that of otheredges of C, then
this edge cannot belong to an MST.
Usefulness -Minimum spanning trees can be computed quickly and easily to provide optimalsolutions. These
trees create a sparse subgraph that reflects a lot about the original graph.
Simplicity -The minimum spanning tree of a weighted graph is nothing but a spanning tree of the graph which
comprises of n–1 edges of minimum total weight. Note that for an unweighted graph, any spanning tree is a minimum
spanning tree.
21.Consider the following undirected graph and draw possible different minimum spanningtrees of it.
23.Consider the following weighted graph and draw possible different minimum spanningtrees of it.
25.Construct a minimum spanning tree of the graph given in Fig. below. Start the Prim’s
algorithm from vertex D.
26.Explain Kruskal’s algorithm used to find the minimum spanning tree.
Kruskal’s algorithm is used to find the minimum spanning tree for a connected weighted graph. The
algorithm aims to find a subset of the edges that forms a tree that includes every vertex. The total weight
of all the edges in the tree is minimized. However, if the graph is not connected,then it finds a minimum
spanning forest. Note that a forest is a collection of trees. Similarly, a minimum spanning forest is a
collection of minimum spanning trees.
Σ In circuit networks where points of connection are drawn as vertices and component wiresbecome
the edges of the graph.
Σ In transport networks where stations are drawn as vertices and routes become the edges of thegraph.
Σ In maps that draw cities/states/regions as vertices and adjacency relations as edges.
Σ In program flow analysis where procedures or modules are treated as vertices and calls to these
procedures are drawn as edges of the graph.
Σ Once we have a graph of a particular concept, they can be easily used for finding shortest paths, project
planning, etc.
Σ In flowcharts or control-flow graphs, the statements and conditions in a program are represented as nodes
and the flow of control is represented by the edges.
Σ In state transition diagrams, the nodes are used to represent states and the edges represent legal moves
from one state to the other.
Σ Graphs are also used to draw activity network diagrams.
Σ the total amount of time needed to complete the project
-TEJAS CHITTE
Linear search, also called as sequential search, is a very simple method used for searching an array for a
particular value. It works by comparing the value to be searched with every elementof the array one by
one in a sequence until a match is found. Linear search is mostly used to search an unordered list of
elements (array in which data elements are not sorted). For example, if an array A[] is declared and
initialized as,
int A[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5}; and the value to be searched is VAL = 7, then searching means to
find whether the value ‘7’ is present in the array or not.
3.Discuss bubble sort in detail, consider an array A[] that has the following elements: A[] =
{30, 52, 29, 87, 63, 27, 19, 54}
Pass 1:
(f) Compare 87 and 19. Since 87 > 19, swapping is done.30, 29, 52,
63, 27, 19, 87, 54
(g) Compare 87 and 54. Since 87 > 54, swapping is done.30, 29, 52,
63, 27, 19, 54, 87
4.Write a program to enter n numbers in an array. Redisplay the array with elements beingsorted in
ascending order.
#include <stdio.h>
#include <conio.h>
int main()
{
int i, n, temp, j, arr[10];
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements: ");
for(i=0;i<n;i++)
{
scanf("%d", &arr [i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n–i–1;j++)
{
if(arr[j] > arr[j+1])
{
temp = arr[j]; arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf("\n The array sorted in ascending order is :\n");
for(i=0;i<n;i++)
printf("%d\t", arr[i]);
getch();
return 0;
}
Output
Enter the number of elements in the array : 10
Enter the elements : 8 9 6 7 5 4 2 3 1 10
The array sorted in ascending order is :
1 2 3 4 5 6 7 8 9 10
5.Consider an array of integers given below. Sort the values in the array using insertion sort and also
discuss the concept of it.
Initially, A[0] is the only element in the sorted set. In Pass 1, A[1] will be placed either before or after A[0], so that
the array A is sorted. In Pass 2, A[2] will be placed either before A[0], in between A[0] and A[1], or after A[1]. In
Pass 3, A[3] will be placed in its proper place. In Pass N–1, A[N–1] will be placed in its proper place to keep the
array sorted.
7.Discuss the concept of selection sort and apply selection sort on given numbers andillustrate the
results.
Selection sort is a sorting algorithm that has a quadratic running time complexity of O(n2), thereby making
it inefficient to be used on large lists. Although selection sort performs worse than insertion sort algorithm,
it is noted for its simplicity and also has performance advantages over more complicated algorithms in
certain situations. Selection sort is generally used for sorting files with very large objects (records) and
small keys.
9.Explain the concept of merge sort and show the merge sort example on followingnumbers.
10.Explain the concept of quick sort.
Quick sort is a widely used sorting algorithm developed by C. A. R. Hoare that makes O(n log n)comparisons in the
average case to sort an array of n elements. However, in the worst case, it hasa quadratic running time given as O(n2).
Basically, the quick sort algorithm is faster than other O(n log n) algorithms, because its efficient implementation can
minimize the probability of requiring quadratic time. Quick sort is also known as partition exchange sort.
Technique
Quick sort works as follows:
1. Set the index of the first element in the array to loc and left variables. Also, set the index of thelast element of the
array to the right variable.
That is, loc = 0, left = 0, and right = n–1 (where n in the number of elements in the array)
2. Start from the element pointed by right and scan the array from right to left, comparing eachelement on the
way with the element pointed by the variable loc.
(a) If that is the case, then simply continue comparing until right becomes equal to loc. Onceright = loc, it
means the pivot has been placed in its correct position.
(b) However, if at any point, we have a[loc] > a[right], then interchange the two values and jumpto Step 3.
In the first pass, the numbers are sorted according to the digit at ones place. The buckets arepictured upside
down as shown below.
After this pass, the numbers are collected bucket by bucket. The new list thus formed is used as an input for the next
pass. In the second pass, the numbers are sorted according to the digit at the tens place. The buckets are pictured upside
down.
In the third pass, the numbers are sorted according to the digit at the hundreds place. The bucketsare pictured upside
down.
The numbers are collected bucket by bucket. The new list thus formed is the final sorted result.After the third
pass, the list can be given as
123, 345, 472, 555, 567, 654, 808, 911, 924.
13.Sort the elements given below using shell sort.
-TEJAS CHITTE