Solved_Unit_4_Q-Bank
Solved_Unit_4_Q-Bank
Solved_Unit_4_Q-Bank
Ans –
Traversing refers to visiting each node in a data structure in a systematic way. Traversal methods
differ between trees and graphs due to their structures. Here are the types of traversal:
Tree Traversal
1. Depth-First Traversal (DFT)
• Explores as far as possible along a branch before backtracking.
• Types:
o Preorder (NLR): Visit Node → Left subtree → Right subtree.
▪ Used for: Copying a tree, evaluating expressions in prefix notation.
o Inorder (LNR): Left subtree → Visit Node → Right subtree.
▪ Used for: Sorting in Binary Search Trees.
o Postorder (LRN): Left subtree → Right subtree → Visit Node.
▪ Used for: Deleting a tree, evaluating expressions in postfix notation.
• Example Of DFT –
1
/ \
2 3
/\
4 5
Preorder: 1 → 2 → 4 → 5 → 3
Inorder: 4 → 2 → 5 → 1 → 3
Postorder: 4 → 5 → 2 → 3 → 1
Disadvantages of a BST
1. Degeneration: If poorly balanced (e.g., inserting sorted elements), a BST can degrade
into a linked list with O(n) complexity for operations.
2. Balancing: Requires self-balancing (e.g., AVL or Red-Black trees) for optimal
performance.
Applications of BST
1. Databases: Indexing and searching records.
2. Compilers: Used in symbol tables to store variable names.
3. Network Routing: Efficient routing and IP lookup.
4. Searching and Sorting:
o BSTs act as a dynamic sorted collection.
5. Autocomplete: Variants like tries and BSTs are used for efficient prefix-based searches.
Example
A BST for the values {10, 5, 15, 3, 7, 12, 18}:
10
/ \
5 15
/ \ / \
3 7 12 18
• Left subtree of 10: {5, 3, 7} (all values < 10).
• Right subtree of 10: {15, 12, 18} (all values > 10).
1. Weighted Graph
• Definition: A graph where every edge has a numerical value (called weight or cost).
• Representation:
o Adjacency Matrix: A 2D array where the value at position [i][j] represents the
weight of the edge from vertex i to j.
o Adjacency List: Each vertex has a list of pairs (neighbor, weight).
Example:
(A)---4---(B)
| |
6| |3
| |
(C)---5---(D)
• Edges have weights like 4, 6, 5, and 3.
• Adjacency Matrix OF Vertices: A,B,C,D
A B C D
A [ 0 4 6 0 ]
B [ 4 0 0 3 ]
C [ 6 0 0 5 ]
D [ 0 3 5 0 ]
• Adjacency List:
A → [(B, 4), (C, 6)]
B → [(A, 4), (D, 3)]
C → [(A, 6), (D, 5)]
D → [(B, 3), (C, 5)]
Ans –
Complete Binary Tree: Detailed Explanation
A Complete Binary Tree is a specialized form of a binary tree with specific structural
properties. Here's an in-depth look at its definition, properties, examples, and applications.
A Complete Binary Tree satisfies the following conditions:
1. All levels, except possibly the last, are completely filled with nodes.
2. Nodes in the last level are aligned as far left as possible.
Properties of a Complete Binary Tree
1. Height:
o The height of a complete binary tree with n nodes is ⌊log2(n)⌋+1.
o Example: A complete binary tree with 15 nodes has a height of ⌊log2(15)⌋+1=4.
2. Node Distribution:
o For a tree of height h, the first h - 1levels are completely filled.
o Nodes in the last level (height h) are filled from left to right.
3. Number of Nodes:
o A complete binary tree with height h has between 2h-1 and 2h−1 nodes:
▪ Minimum nodes: 2h-1 (when the last level has only one node).
▪ Maximum nodes: 2h−1 (when all levels are fully filled).
4. Efficient Storage:
o A complete binary tree can be stored efficiently in an array (or list) without
pointers or references:
▪ Parent of a node at index i: (i−1)//2.
▪ Left child: 2i+1.
▪ Right child: 2i+2.
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
Explanation:
1. Levels:
o Level 1: Fully filled (Node 1).
o Level 2: Fully filled (Nodes 2, 3).
o Level 3: Fully filled (Nodes 4, 5, 6, 7).
o Level 4: Partially filled (Nodes 8 and 9), aligned from left to right.
2. Nodes:
o Total number of nodes = 9.
o Height of the tree (h) = ⌊log2(9)⌋+1=4.
Ans –
Q6. Explain the AVL tree insertion and deletion with suitable example.
Ans –
AVL Tree: Overview
An AVL tree is a self-balancing binary search tree where the difference between the
heights of the left and right subtrees of any node (called the balance factor) is at most 1. This
ensures that the tree remains approximately balanced, resulting in O(log n) time complexity for
search, insertion, and deletion operations.
Key Concepts
1. Balance Factor:
Balance Factor = Height of Left Subtree - Height of Right Subtree
o Valid balance factor: −1,0,+1.
o If the balance factor exceeds these limits, rotations are used to rebalance.
2. Rotations:
o Used to restore balance after insertion or deletion.
o Types of rotations:
▪ Right Rotation (RR): Corrects left-heavy imbalance.
▪ Left Rotation (LL): Corrects right-heavy imbalance.
▪ Left-Right Rotation (LR): Corrects left-right imbalance.
▪ Right-Left Rotation (RL): Corrects right-left imbalance.
Ans –
The Tree Terminologies:
1. Node
• A node is a fundamental unit of a tree.
• It contains:
o Data: Information stored in the node.
o Pointers: References to its child nodes (left, right, or more, depending on the tree
type).
• Example: In a binary tree:
10
/ \
5 20
o 10, 5, and 20 are nodes.
2. Root
• The root is the topmost node of the tree and serves as the entry point.
• A tree has exactly one root.
• It has no parent.
• Example: In the tree:
10
/ \
5 20
o 10 is the root.
4. Siblings
• Siblings are nodes that share the same parent.
• Example:
10
/ \
5 20
o 5 and 20 are siblings because they share the same parent (10).
5. Leaf (or External Node)
• A leaf node is a node that has no children.
• It is the end of a path in the tree.
• Example:
10
/ \
5 20
/
3
o 3 and 20 are leaf nodes because they have no children.
6. Internal Node
• An internal node is any node with at least one child.
• Example:
10
/ \
5 20
/
3
o 10 and 5 are internal nodes because they have children.
7. Degree
• The degree of a node is the number of children it has.
• The degree of a tree is the maximum degree of any node in the tree.
• Example:
10
/ \
5 20
/
3
o Degree of 10: 2 (it has two children, 5 and 20).
o Degree of 5: 1 (it has one child, 3).
o Degree of 20: 0 (it has no children).
8. Level
• The level of a node is its distance from the root, measured in edges.
• The root is at level 0, its children at level 1, and so on.
• Example:
10 (Level 0)
/ \
5 20 (Level 1)
/
3 (Level 2)
9. Height
• The height of a node is the number of edges in the longest path from that node to a leaf.
• The height of a tree is the height of the root node.
• Example:
10
/ \
5 20
/
3
o Height of 3: 0 (it’s a leaf).
o Height of 5: 1 (path: 5 → 3).
o Height of the tree: 2 (path: 10 → 5 → 3).
10. Depth
• The depth of a node is the number of edges from the root to that node.
• Example:
10
/ \
5 20
/
3
o Depth of 10: 0.
o Depth of 5: 1.
o Depth of 3: 2.
11. Path
• A path is a sequence of nodes connected by edges.
• Example: In the tree:
10
/ \
5 20
/
3
o Path from 10 to 3: 10 → 5 → 3.
5
/
3
Q8. Create a binary search tree for the following numbers start from an empty binary
search tree. 45,26,10,60,70,30,40 Delete keys 10,60 and 45 one after the other and show
the trees at each stage.
Ans –
Let's go step by step to create the Binary Search Tree (BST) and perform the deletions
as requested. We will start with an empty BST and insert the following numbers: 45, 26, 10, 60,
70, 30, 40. After that, we will delete 10, 60, and 45, one by one, and show the tree at each stage.
1. Insert 45:
Start with an empty tree and insert 45. Since it's the first node, it becomes the root.
45
2. Insert 26:
• 26 is less than 45, so it will be inserted to the left of 45.
45
/
26
3. Insert 10:
• 10 is less than 45, so we go left to 26.
• 10 is also less than 26, so it is inserted as the left child of 26.
45
/
26
/
10
4. Insert 60:
• 60 is greater than 45, so it is inserted as the right child of 45.
45
/ \
26 60
/
10
5. Insert 70:
• 70 is greater than 45, so we go right to 60.
• 70 is greater than 60, so it is inserted as the right child of 60.
45
/ \
26 60
/ \
10 70
6. Insert 30:
• 30 is less than 45, so we go left to 26.
• 30 is greater than 26, so it is inserted as the right child of 26.
45
/ \
26 60
/ \ \
10 30 70
7. Insert 40:
• 40 is less than 45, so we go left to 26.
• 40 is greater than 26, so we go right to 30.
• 40 is greater than 30, so it is inserted as the right child of 30.
45
/ \
26 60
/ \ \
10 30 70
\
40
Delete 60:
• 60 has one child (right child 70), so we replace 60 with its right child 70.
45
/ \
26 70
\
30
\
40
Delete 45:
• 45 has two children (26 and 70). We replace 45 with its in-order successor, which is the
smallest node in its right subtree (in this case, 70).
• After replacement, we remove 70.
70
/
26
\
30
\
40
This is the final tree after performing all insertions and deletions. Each step has been shown to
clearly illustrate how the tree evolves.
Q9. Constructing a expression tree of given expression abc*+e*f+
Ans – ( Below Explanation Is Just For Understanding In Exam Just Draw The Tree )
Steps to Construct the Expression Tree:
Step 1: Start with an empty stack.
We process the expression character by character.
Ans – Hashing
Hashing is a process of mapping data (keys) into a fixed-size value (called a hash or hash
code) using a mathematical function called a hash function. This value serves as an index to
store and retrieve data efficiently in a data structure, commonly a hash table.
Purpose of Hashing
1. Fast Data Retrieval: Hashing allows for near-instantaneous data access.
2. Efficient Storage: Data is distributed across a table to reduce collisions and maximize
storage efficiency.
3. Applications: Hashing is widely used in:
o Databases for indexing.
o Cryptography.
o Caches.
o Hashmaps and sets in programming.
Advantages of Hashing
• Fast data retrieval and insertion (O(1) on average).
• Efficient memory utilization.
Disadvantages of Hashing
• Collisions may degrade performance.
• Poor choice of hash function can lead to uneven distribution.
• Not suitable for ordered data retrieval.
Types Of Hashing
Static Hashing and Dynamic Hashing are two approaches to implementing hash
tables based on how they handle data growth and storage management.
1. Static Hashing
Definition:
In static hashing, the size of the hash table is fixed at the time of creation. Keys are
mapped to a fixed number of slots using a hash function. Once the table is created, it cannot
grow or shrink dynamically.
2. Dynamic Hashing
Definition:
In dynamic hashing, the hash table can grow or shrink dynamically as the number of
keys increases or decreases. This approach is especially useful when the size of the dataset is
unpredictable.
How Dynamic Hashing Works:
Dynamic hashing uses advanced techniques like extendible hashing or linear hashing to
resize the table dynamically, ensuring minimal collisions and efficient utilization of memory.
1. Extendible Hashing:
o Maintains a directory of pointers to buckets.
o The directory size grows when the table needs to expand.
o If a bucket overflows, it is split into two buckets, and the directory is updated.
2. Linear Hashing:
o Incrementally splits the hash table into new buckets as data grows.
o Instead of rehashing the entire table, new keys are distributed into a subset of the
table.
3. Incremental Resizing:
o With techniques like linear hashing, only a portion of the table is resized,
minimizing computational overhead.
Ans –
Depth-First Traversal (DFS) and Breadth-First Traversal (BFS) are two fundamental
graph traversal algorithms used to explore nodes and edges systematically. These techniques
differ in their approach to visiting nodes.
Steps of DFS:
1. Start from the given node (usually the root or any starting node).
2. Mark the node as visited.
3. Explore one adjacent node that hasn’t been visited.
4. Repeat the process recursively for the unvisited nodes.
5. Backtrack when no unvisited adjacent nodes remain.
DFS Example:
Consider the following graph:
A
/ \
B C
/ \
D E
Performing DFS starting from A:
• Start at A: Visited = {A}
• Go to B: Visited = {A, B}
• Go to D: Visited = {A, B, D}
• Backtrack to B, then visit E: Visited = {A, B, D, E}
• Backtrack to A, then visit C: Visited = {A, B, D, E, C}
DFS Output: A → B → D → E → C
Applications of DFS:
1. Finding Connected Components: Useful in undirected graphs.
2. Pathfinding: DFS is a key component in algorithms like backtracking and maze-solving.
3. Topological Sorting: Used in directed acyclic graphs.
4. Cycle Detection: Helps detect cycles in graphs.
Advantages of DFS:
1. Requires less memory than BFS (uses only the recursion stack or a single stack
explicitly).
2. Can find paths in scenarios where the target node is deep in the graph.
Disadvantages of DFS:
1. May explore unnecessary paths, especially in large graphs.
2. Cannot guarantee the shortest path in unweighted graphs.
Steps of BFS:
1. Start from the given node.
2. Mark the node as visited and enqueue it.
3. Dequeue a node from the queue and visit all its unvisited neighbors.
4. Mark the neighbors as visited and enqueue them.
5. Repeat until the queue is empty.
BFS Example:
Using the same graph as above:
A
/ \
B C
/ \
D E
Performing BFS starting from A:
• Start at A: Visited = {A}
• Enqueue neighbors B and C: Queue = [B, C]
• Dequeue B and enqueue neighbors D and E: Queue = [C, D, E]
• Dequeue C: Queue = [D, E]
• Dequeue D: Queue = [E]
• Dequeue E: Queue = []
BFS Output: A → B → C → D → E
Applications of BFS:
1. Shortest Path in Unweighted Graphs: Guarantees the shortest path between nodes.
2. Level Order Traversal: Commonly used in tree traversals.
3. Finding Connected Components: In undirected graphs.
4. Networking: Used in finding the shortest route between devices.
Advantages of BFS:
1. Guarantees the shortest path in unweighted graphs.
2. Explores all neighbors systematically.
Disadvantages of BFS:
1. Requires more memory than DFS (stores all neighbors in the queue).
2. Can be slower in very large graphs.
Q12. Write a FindMin and FindMax function in Tree?
Ans –
struct TreeNode {
int value;
struct TreeNode* left;
struct TreeNode* right;
};
FindMin Function
FindMax Function
7
/ \
2 9
/ \ /
0 5 8
\ \
1 6