0% found this document useful (0 votes)
48 views14 pages

Notes

Uploaded by

imuu8750
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)
48 views14 pages

Notes

Uploaded by

imuu8750
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/ 14

Important questions and answers

Unit 4

Q. 1. What is a binary tree?

A binary tree is a hierarchical data structure in which each node has at most two children, referred to
as the left child and the right child.

Q. 2. What are the types of binary trees?

1. Full Binary Tree: Every node has either 0 or 2 children.


2. Perfect Binary Tree: All internal nodes have two children, and all leaf nodes are at the same
level.
3. Complete Binary Tree: All levels except possibly the last are completely filled, and the
nodes are as far left as possible.
4. Skewed Binary Tree: All nodes have only one child, either left or right.
5. Balanced Binary Tree: The height of the left and right subtrees of every node differs by at
most one.

Q. 3. What is the height of a binary tree?

The height of a binary tree is the number of edges on the longest path from the root to a leaf node.
The height of an empty tree is -1.

Q. 4. What is the difference between binary tree and binary search tree (BST)?

• Binary Tree: A general tree structure where nodes have at most two children.
• Binary Search Tree: A binary tree where:
o The left child contains values less than the parent node.
o The right child contains values greater than the parent node.

Q. What are the main types of binary tree traversal?

1. Depth-First Traversal (DFT):


o Inorder (Left, Root, Right)
o Preorder (Root, Left, Right)
o Postorder (Left, Right, Root)
2. Breadth-First Traversal (BFT):
o Level-order Traversal (nodes visited level by level).

Q. What is Inorder Traversal?

In Inorder Traversal, nodes are visited in the order:

1. Visit the left subtree.


2. Visit the root.
3. Visit the right subtree.
Q. What is Preorder Traversal?

In Preorder Traversal, nodes are visited in the order:

1. Visit the root.


2. Visit the left subtree.
3. Visit the right subtree.

Q. How do you traverse a binary tree?

Traversal methods:

1. Inorder (Left, Root, Right):

scss
Copy code
void inorder(Node* root) {
if (root != NULL) {
inorder(root->left);
print(root->data);
inorder(root->right);
}
}

2. Preorder (Root, Left, Right):

scss
Copy code
void preorder(Node* root) {
if (root != NULL) {
print(root->data);
preorder(root->left);
preorder(root->right);
}
}

3. Postorder (Left, Right, Root):

scss
Copy code
void postorder(Node* root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
print(root->data);
}
}

4. Level-order (Breadth-First): Use a queue to traverse the tree level by level.

Q. 6. What is the maximum number of nodes in a binary tree of height h?

The maximum number of nodes in a binary tree of height h is: 2h+1−1.

Q. What is the time complexity of searching in a binary search tree?


• Best Case: O(log n), for a balanced BST.
• Worst Case: O(n), for a skewed BST.

Q. What is Height balanced AVL Tree


AVL Tree can be defined as height balanced binary search tree in which 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.

What if the input to binary search tree comes in a sorted (ascending or descending) manner? It will
then look like this −

It is observed that BST's worst-case performance is closest to linear search algorithms, that is Ο(n).
In real-time data, we cannot predict data pattern and their frequencies. So, a need arises to balance
out the existing BST.
Named after their inventor Adelson, Velski & Landis, AVL trees are height balancing binary
search tree. AVL tree checks the height of the left and the right sub-trees and assures that the
difference is not more than 1. This difference is called the Balance Factor.
Here we see that the first tree is balanced and the next two trees are not balanced −

In the second tree, the left subtree of C has height 2 and the right subtree has height 0, so the
difference is 2. In the third tree, the right subtree of A has height 2 and the left is missing, so it is 0,
and the difference is 2 again. AVL tree permits difference (balance factor) to be only 1.
BalanceFactor = height(left-sutree) − height(right-sutree)
If the difference in the height of left and right sub-trees is more than 1, the tree is balanced using
some rotation techniques.

Q. What are AVL Rotations?


To balance itself, an AVL tree may perform the following four kinds of rotations −

• Left rotation
• Right rotation
• Left-Right rotation
• Right-Left rotation
The first two rotations are single rotations and the next two rotations are double rotations. To have
an unbalanced tree, we at least need a tree of height 2. With this simple tree, let's understand them
one by one.

Left Rotation
If a tree becomes unbalanced, when a node is inserted into the right subtree of the right subtree, then
we perform a single left rotation −

In our example, node A has become unbalanced as a node is inserted in the right subtree of A's right
subtree. We perform the left rotation by making A the left-subtree of B.

Right Rotation
AVL tree may become unbalanced, if a node is inserted in the left subtree of the left subtree. The
tree then needs a right rotation.
As depicted, the unbalanced node becomes the right child of its left child by performing a right
rotation.

Left-Right Rotation
Double rotations are slightly complex version of already explained versions of rotations. To
understand them better, we should take note of each action performed while rotation. Let's first
check how to perform Left-Right rotation. A left-right rotation is a combination of left rotation
followed by right rotation.

State Action

A node has been inserted into the right subtree of the left
subtree. This makes C an unbalanced node. These scenarios
cause AVL tree to perform left-right rotation.

We first perform the left rotation on the left subtree of C. This


makes A, the left subtree of B.

Node C is still unbalanced, however now, it is because of the


left-subtree of the left-subtree.
We shall now right-rotate the tree, making B the new root node
of this subtree. C now becomes the right subtree of its own left
subtree.

The tree is now balanced.

Right-Left Rotation
The second type of double rotation is Right-Left Rotation. It is a combination of right rotation
followed by left rotation.

State Action

A node has been inserted into the left subtree of the right subtree.
This makes A, an unbalanced node with balance factor 2.

First, we perform the right rotation along C node, making C the


right subtree of its own left subtree B. Now, B becomes the right
subtree of A.
Node A is still unbalanced because of the right subtree of its right
subtree and requires a left rotation.

A left rotation is performed by making B the new root node of the


subtree. A becomes the left subtree of its right subtree B.

The tree is now balanced.

Q. Explain the fundamentals of Tree Sort.


Tree sort is a sorting algorithm that is based on Binary Search Tree data structure. It first creates a
binary search tree from the elements of the input list or array and then performs an in-order traversal
on the created binary search tree to get the elements in sorted order.

Algorithm:

Step 1: Take the elements input in an array.


Step 2: Create a Binary search tree by inserting data items from the array into the
binary search tree.
Step 3: Perform in-order traversal on the tree to get the elements in sorted order.

Q. What is the time complexity of binary tree traversal?

• All traversals (Inorder, Preorder, Postorder, Level-order) have a time complexity of O(n)
because each node is visited exactly once.
Q. What are some real-world applications of tree traversal?

1. Expression Parsing: Postorder traversal is used to evaluate expressions in an expression tree.


2. Directory Management: Preorder traversal is used to list files and directories.
3. Search Operations: Inorder traversal is used to retrieve sorted data from a binary search tree.
4. Data Serialization: Preorder or Level-order traversal is used for serialization/deserialization
of trees.

Q. What is the difference between DFS and BFS in binary tree traversal?

Aspect DFS (Depth-First Search) BFS (Breadth-First Search)


Traversal Type Explores depth (child nodes) first. Explores breadth (level by level).
Techniques Inorder, Preorder, Postorder. Level-order Traversal.
Implementation Uses recursion or a stack. Uses a queue.
Space Complexity O(h) for recursion or O(n) O(w), where www is the width.

Q. What is a graph in data structures?

A graph is a data structure that consists of:

1. Vertices (Nodes): Fundamental units of the graph.


2. Edges (Connections): Links between vertices.

Graphs can represent various relationships, such as roads connecting cities, social networks, or
dependencies in tasks.

Q. What are the types of graphs?

1. Directed Graph (Digraph): Edges have a direction, e.g., A → B.


2. Undirected Graph: Edges have no direction, e.g., A — B.
3. Weighted Graph: Edges have weights (values) representing costs, distances, etc.
4. Unweighted Graph: Edges do not have weights.
5. Connected Graph: Every vertex is reachable from any other vertex.
6. Disconnected Graph: At least one vertex is not reachable from another vertex.
7. Cyclic Graph: Contains at least one cycle.
8. Acyclic Graph: Does not contain any cycles.
9. Bipartite Graph: Vertices can be divided into two disjoint sets such that no two vertices
within the same set are adjacent.

Q. What are the ways to represent a graph in memory?

1. Adjacency Matrix:
o A 2D matrix where matrix[i][j] represents the presence (1) or absence (0) of an
edge between vertices i and j.
o Space Complexity: O(V2), where V is the number of vertices.
2. Adjacency List:
o Each vertex has a list of adjacent vertices.
o Space Complexity: O(V+E), where EEE is the number of edges.
3. Edge List:
o A list of all edges, e.g., [(A, B), (B, C)].
Q. What is a weighted graph?

A weighted graph is a graph where edges have weights, representing the cost or distance between
vertices.

Q. What is the difference between BFS and DFS?

Aspect Breadth-First Search (BFS) Depth-First Search (DFS)


Traversal Order Explores all neighbors level Explores as far as possible along one branch
by level. before backtracking.
Data Structure Queue Stack (or recursion).
Used
Time Complexity O(V+E) O(V+E)
Use Cases Finding shortest path Detecting cycles or connectivity.
(unweighted).

Q. How do you detect a cycle in a graph?

1. For Directed Graphs:


o Use DFS with a recursion stack to detect back edges.
2. For Undirected Graphs:
o Use DFS to check if a visited node is revisited without being the parent.

Q. What is a spanning tree in a graph?

A spanning tree of a connected graph is a subgraph that:

1. Includes all vertices of the graph.


2. Is a tree (no cycles).
3. Has exactly V−1 edges, where V is the number of vertices.

Q. What are MST algorithms?

MST (Minimum Spanning Tree) algorithms find the spanning tree with the minimum total edge
weight:

1. Prim's Algorithm:
o Greedy algorithm; starts with a single vertex and adds edges with the smallest weight.
2. Kruskal's Algorithm:
o Greedy algorithm; sorts edges by weight and adds edges without forming a cycle.

Q. How do you implement BFS and DFS?


BFS (Using Queue):

python
Copy code
def bfs(graph, start):
visited = set()
queue = [start]
visited.add(start)
while queue:
vertex = queue.pop(0)
print(vertex, end=' ')
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)

DFS (Using Recursion):

python
Copy code
def dfs(graph, node, visited):
if node not in visited:
print(node, end=' ')
visited.add(node)
for neighbor in graph[node]:
dfs(graph, neighbor, visited)

Q. What is the difference between a tree and a graph?

Aspect Tree Graph


Structure A tree is a connected, acyclic graph. A graph can have cycles or be disconnected.
Edges V−1 edges for V vertices. Can have any number of edges.
Root Has a root node. No concept of a root.

Q. For following graph find MST using Prims algorithm.


2 3
A ------- B ------- C
\ | /
6 8| 5
\ | /
D --------- E
7

Steps of Prim's Algorithm

1. Initialization:
o Start with any vertex (let’s choose A as the starting vertex).
o Mark it as part of the MST.
o Add all its edges to a priority queue or sorted list based on weights.
2. Step-by-step Execution:
o Pick the smallest edge that connects a vertex in the MST to a vertex outside it.
o Add the corresponding edge and vertex to the MST.
o Repeat until all vertices are included in the MST.
Table of Progression

Step Current MST Edges Added Edge (Weight) Vertices in MST Edges Considered (Min)
1 - A → B (2) A, B A → B (2), A → D (6)
2 A→B B → C (3) A, B, C B → C (3), B → E (8)
3 A → B, B → C C → E (5) A, B, C, E C → E (5), E → D (7)
4 A → B, B → C, C → E A → D (6) A, B, C, E, D -

Result

The MST for this graph includes the edges:

• A → B (2)
• B → C (3)
• C → E (5)
• A → D (6)

Total weight of the MST = 2+3+5+6=16

Q. What are common applications of graphs?

1. Social Networks: Representing relationships between people.


2. Navigation Systems: Finding shortest paths (e.g., Google Maps).
3. Web Crawling: Representing hyperlinks between pages.
4. Task Scheduling: Dependency resolution using DAGs.
5. Network Routing: Optimizing data transfer paths.

Unit 5

Q. What is Hashing ?

Hashing is a technique or process of mapping keys, values into the hash table by using a hash
function. It is done for faster access to elements. The efficiency of mapping depends on the efficiency
of the hash function used. Let a hash function H(x) maps the value.

Practice Problems on Hashing


Hashing is a technique or process of mapping keys, values into the hash table by using a hash function.
It is done for faster access to elements. The efficiency of mapping depends on the efficiency of the hash
function used.
Let a hash function H(x) maps the value at the index x%10 in an Array. For example if the list of
values is [11,12,13,14,15] it will be stored at positions {1,2,3,4,5} in the array or Hash table
respectively.
Q. What is a hash function?
A hash function is a function that takes a set of inputs of any arbitrary size and fits them into a table
or other data structure that contains fixed-size elements. The table or data structure generated is
usually called a hash table.

A hash function is a mathematical function that takes an input (or "key") and converts it into a fixed-
size string of characters, typically a sequence of numbers or letters, which represents the input in a
more compact and standardized form. The output of a hash function is called the hash value, hash
code, or simply hash.

Characteristics of a Hash Function:

1. Deterministic: The same input always produces the same output.


2. Fast Computation: The hash value should be computed efficiently.
3. Uniform Distribution: Hash values should be evenly distributed across the output space to
minimize collisions.
4. Collision Resistance:
o Pre-image resistance: It should be computationally hard to find the input from its
hash value.
o Collision resistance: It should be difficult to find two different inputs that produce the
same hash value.
5. Fixed Output Size: Regardless of the input size, the hash value has a fixed length.

Uses of Hash Functions:

1. Data Structures:
o Used in hash tables for efficient data retrieval, insertion, and deletion.
o Example: The key-value pairs in a dictionary or hashmap rely on hash functions to
quickly locate data.
2. Data Integrity:
o Hash functions verify the integrity of data by comparing the hash values before and
after transmission.
o Example: File checksum validation (e.g., MD5, SHA-256).
3. Cryptography:
o Used in secure password storage, digital signatures, and message authentication codes
(e.g., SHA-256, SHA-3).
o Properties like collision resistance make cryptographic hash functions secure.
4. Database Indexing:
o Hash functions are used for indexing data efficiently in large databases.
5. Load Balancing:
o Hash functions distribute tasks or requests across servers evenly in distributed
systems.
6. Distributed Systems:
o Used in consistent hashing for distributed data storage and retrieval (e.g., in systems
like Cassandra and DynamoDB).
7. Image and Video Processing:
o Hashing can identify duplicate files by comparing their hash values.

Q. What are Key Challenges of Hash Functions?

1. Collisions: When two inputs produce the same hash value, it’s called a collision. Collision-
handling techniques include chaining, open addressing, and double hashing.
2. Security: Cryptographic hash functions must resist vulnerabilities like pre-image attacks and
collision attacks.
3. Uniformity: A good hash function ensures that hash values are evenly distributed to avoid
clustering in hash tables.

Hash functions are foundational in computer science, used across a wide range of applications to
ensure efficient, secure, and reliable operations.

Q. What do you understand by Hash Collision?

A collision occurs when more than one value to be hashed by a particular hash function hash to the
same slot in the table or data structure (hash table) being generated by the hash function.

Example Hash Table with Collisions:


Let us take the exact same hash function from before: take the value to be hashed mod 10 and place it
in that slot in the hash table.
Numbers to hash: 22, 9, 14, 17, 42
As before, the hash table is shown.
As before, we hash each value as it appears in the string of values to hash, starting with the first
value. The first four values can be entered into the hash table without any issues. It is the last
value, 42, however, that causes a problem. 42 mod 10 = 2, but there is already a value in slot 2 of the
hash table, namely 22. This is a collision.
The value 42 must end up in one of the hash table’s slots, but arbitrary assigning it a slot at random
would make accessing data in a hash table much more time consuming, as we obviously want to
retain the constant time growth of accessing our hash table. There are two common ways to deal with
collisions: chaining, and open addressing.
Collision Handling: Since a hash function gets us a small number for a big key, there is possibility
that two keys result in same value. The situation where a newly inserted key maps to an already
occupied slot in hash table is called collision and must be handled using some collision handling
technique.

You might also like