Umer Major
Umer Major
Answer:
Tree 1
In-order: D G B E H I F C A
Pre-order: A B D G E C F H I
Post-order: G D E H I F C B A
Tree 2
In-order: 5 4 8 11 10 17 19 31 43 49
Pre-order: 11 4 5 8 19 17 10 31 43 49
Post-order: 5 4 8 10 17 31 43 49 19 11
Tree 3
In-order: I D J B F G H K C A
Pre-order: A B D I J C F G H K
Post-order: I J D B F K H G C A
Q2
Answer:
Steps for constructing the Binary Search Tree:
1. Start with Pre-order Traversal: The first element of the pre-order
traversal is the root of the tree. From the given pre-order sequence,
we know that the root of the tree is 12.
Final Tree:
12
/ \
8 20
/\ /\
4 10 14 22
Q.3
Answer:
Min-Heap Implementation
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class MinHeap {
private:
vector<int> heap;
if (smallest != index) {
swap(heap[index], heap[smallest]);
heapifyDown(smallest);
}
}
public:
void insert(int value) {
heap.push_back(value);
heapifyUp(heap.size() - 1);
display();
}
void deleteMin() {
if (heap.empty()) return;
swap(heap[0], heap[heap.size() - 1]);
heap.pop_back();
heapifyDown(0);
display();
}
void display() {
for (int val : heap) cout << val << " ";
cout << endl;
}
};
int main() {
MinHeap minHeap;
minHeap.insert(3);
minHeap.insert(2);
minHeap.insert(15);
minHeap.deleteMin();
}
Max-Heap Implementation:
cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class MaxHeap {
private:
vector<int> heap;
if (largest != index) {
swap(heap[index], heap[largest]);
heapifyDown(largest);
}
}
public:
void insert(int value) {
heap.push_back(value);
heapifyUp(heap.size() - 1);
display();
}
void deleteMax() {
if (heap.empty()) return;
swap(heap[0], heap[heap.size() - 1]);
heap.pop_back();
heapifyDown(0);
display();
}
void display() {
for (int val : heap) cout << val << " ";
cout << endl;
}
};
int main() {
MaxHeap maxHeap;
maxHeap.insert(3);
maxHeap.insert(2);
maxHeap.insert(15);
maxHeap.deleteMax();
}
Q.4
Answer:
Insertion Sort
cpp
#include <iostream>
using namespace std;
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
display(arr, n);
}
Bubble Sort
cpp
#include <iostream>
using namespace std;
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
display(arr, n);
}
Heap Sort
#include <iostream>
using namespace std;
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
display(arr, n);
}
Quick Sort
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
display(arr, n);
}