0% found this document useful (0 votes)
16 views29 pages

Document

The document contains code snippets for various data structures and algorithms related to graphs and trees: - It defines a BinaryTree class with insert and root node functionality - It shows inorder, preorder, and postorder traversal functions for a binary tree - It implements a MaxHeap class with insert and extract max methods - It defines directed and undirected graph classes using adjacency lists - It shows a weighted graph implementation using pairs of vertices and weights - It includes Dijkstra's algorithm for finding shortest paths in a graph

Uploaded by

farhan khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views29 pages

Document

The document contains code snippets for various data structures and algorithms related to graphs and trees: - It defines a BinaryTree class with insert and root node functionality - It shows inorder, preorder, and postorder traversal functions for a binary tree - It implements a MaxHeap class with insert and extract max methods - It defines directed and undirected graph classes using adjacency lists - It shows a weighted graph implementation using pairs of vertices and weights - It includes Dijkstra's algorithm for finding shortest paths in a graph

Uploaded by

farhan khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

[03-01, 11:02 a.m.

] 💔: Binary tree

[03-01, 11:03 a.m.] 💔: #include <iostream>

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

Node(int value) : data(value), left(nullptr), right(nullptr) {}


};

class BinaryTree {
private:
Node* root;

void insertHelper(Node* root, int value) {


if (value < root->data) {
if (root->left == nullptr) {
root->left = new Node(value);
} else {
insertHelper(root->left, value);
}
} else {
if (root->right == nullptr) {
root->right = new Node(value);
} else {
insertHelper(root->right, value);
}
}
}

public:
BinaryTree() : root(nullptr) {}

void insert(int value) {


if (root == nullptr) {
root = new Node(value);
} else {
insertHelper(root, value);
}
}
};

int main() {
BinaryTree tree;

tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(1);
tree.insert(4);

return 0;
}
[03-01, 11:08 a.m.] 💔: In order

[03-01, 11:08 a.m.] 💔: #include <iostream>

using namespace std;

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

Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};

void inorderTraversal(Node* root) {


if (root == nullptr) {
return;
}

inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}

int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);

cout << "Inorder Traversal: ";


inorderTraversal(root);

return 0;
}

[03-01, 11:09 a.m.] 💔: Pre order

[03-01, 11:09 a.m.] 💔: #include <iostream>

using namespace std;

struct Node {
int data;
Node* left;
Node* right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};

void preorderTraversal(Node* root) {


if (root == nullptr) {
return;
}
cout << root->data << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}

int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);

cout << "Preorder Traversal: ";


preorderTraversal(root);

return 0;
}

[03-01, 11:10 a.m.] 💔: Postorder

[03-01, 11:10 a.m.] 💔: #include <iostream>

using namespace std;

struct Node {
int data;
Node* left;
Node* right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
void postorder(Node* root) {
if (root == nullptr) {
return;
}
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
}

int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);

cout << "Postorder traversal: ";


postorder(root);

return 0;
}

[03-01, 11:12 a.m.] 💔: Avl.B.tree

[03-01, 11:12 a.m.] 💔: #include <iostream>

using namespace std;

class Node {
public:
int *keys;
int t;
Node **C;
int n;
bool leaf;
Node(int _t, bool _leaf);
void insertNonFull(int k);
void splitChild(int i, Node *y);
void traverse();
Node *search(int k);
friend class Tree;
};

class Tree {
public:
Node *root;
int t;
Tree(int _t);
void insert(int k);
void traverse();
Node *search(int k);
};

Node::Node(int t1, bool leaf1) {


t = t1;
leaf = leaf1;
keys = new int[2*t-1];
C = new Node *[2*t];
n = 0;
}

void Node::traverse() {
int i;
for (i = 0; i < n; i++) {
if (leaf == false)
C[i]->traverse();
cout << " " << keys[i];
}
if (leaf == false)
C[i]->traverse();
}

Node *Node::search(int k) {
int i = 0;
while (i < n && k > keys[i])
i++;
if (keys[i] == k)
return this;
if (leaf == true)
return NULL;
return C[i]->search(k);
}

void Tree::traverse() {
if (root != NULL)
root->traverse();
}

Node *Tree::search(int k) {
return (root == NULL) ? NULL : root->search(k);
}

int main() {
Tree t(3);
t.insert(10

[03-01, 11:13 a.m.] 💔: Max heap

[03-01, 11:13 a.m.] 💔: #include <iostream>

#include <vector>
#include <algorithm>

class MaxHeap {
private:
std::vector<int> heap;

void heapify(int index) {


int largest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;

if (left < heap.size() && heap[left] > heap[largest]) {


largest = left;
}

if (right < heap.size() && heap[right] > heap[largest]) {


largest = right;
}

if (largest != index) {
std::swap(heap[index], heap[largest]);
heapify(largest);
}
}

public:
void insert(int value) {
heap.push_back(value);
int index = heap.size() - 1;

while (index > 0 && heap[index] > heap[(index - 1) / 2]) {


std::swap(heap[index], heap[(index - 1) / 2]);
index = (index - 1) / 2;
}
}

int extractMax() {
if (heap.empty()) {
throw std::out_of_range("Heap is empty");
}
int max = heap[0];
heap[0] = heap.back();

[03-01, 11:15 a.m.] 💔: Directed graph

[03-01, 11:15 a.m.] 💔: #include <iostream>

#include <list>
using namespace std;

class Graph {
int V;
list<int> *adj;

public:
Graph(int V);
void addEdge(int v, int w);
void printGraph();
};

Graph::Graph(int V) {
this->V = V;
adj = new list<int>[V];
}

void Graph::addEdge(int v, int w) {


adj[v].push_back(w);
}
void Graph::printGraph() {
for (int i = 0; i < V; ++i) {
cout << "Adjacency list of vertex " << i << "\nhead";
for (auto x : adj[i])
cout << " -> " << x;
cout << endl;
}
}

int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

g.printGraph();

return 0;
}

[03-01, 11:15 a.m.] 💔: Undirected graph

[03-01, 11:15 a.m.] 💔: #include <iostream>

#include <list>
class Graph {
int V;
std::list<int> *adj;

public:
Graph(int V);
void addEdge(int v, int w);
void printGraph();
};

Graph::Graph(int V) {
this->V = V;
adj = new std::list<int>[V];
}

void Graph::addEdge(int v, int w) {


adj[v].push_back(w);
adj[w].push_back(v);
}

void Graph::printGraph() {
for (int i = 0; i < V; ++i) {
std::cout << "Adjacency list of vertex " << i << "\n";
std::cout << "head";
for (int val : adj[i]) {
std::cout << " -> " << val;
}
std::cout << std::endl;
}
}

int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(1, 3);

g.printGraph();

return 0;
}

[03-01, 11:16 a.m.] 💔: Weighted

[03-01, 11:16 a.m.] 💔: #include <iostream>

#include <vector>
#include <utility>

using namespace std;

class WeightedGraph {
private:
int V;
vector<pair<int, int>> *adj;

public:
WeightedGraph(int V) {
this->V = V;
adj = new vector<pair<int, int>>[V];
}

void addEdge(int u, int v, int weight) {


adj[u].push_back(make_pair(v, weight));
adj[v].push_back(make_pair(u, weight)); // For undirected graph
}

void printGraph() {
for (int i = 0; i < V; ++i) {
cout << "Vertex " << i << " is connected to:\n";
for (auto& edge : adj[i]) {
cout << edge.first << " with weight " << edge.second << "\n";
}
cout << "\n";
}
}
};

int main() {
WeightedGraph graph(4);
graph.addEdge(0, 1, 5);
graph.addEdge(0, 2, 3);
graph.addEdge(1, 2, 2);
graph.addEdge(1, 3, 8);
graph.addEdge(2, 3, 1);

graph.printGraph();

return 0;
}

[03-01, 11:16 a.m.] 💔: Unweighted

[03-01, 11:17 a.m.] 💔: #include <iostream>

#include <list>

class Graph {
int V;
std::list<int> *adj;

public:
Graph(int V);
void addEdge(int v, int w);
void printGraph();
};

Graph::Graph(int V) {
this->V = V;
adj = new std::list<int>[V];
}

void Graph::addEdge(int v, int w) {


adj[v].push_back(w);
}

void Graph::printGraph() {
for (int i = 0; i < V; ++i) {
std::cout << "Adjacency list of vertex " << i << "\nhead";
for (int x : adj[i])
std::cout << " -> " << x;
std::cout << std::endl;
}
}

int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);

g.printGraph();

return 0;
}
[03-01, 11:18 a.m.] 💔: Dijestra graph

[03-01, 11:19 a.m.] 💔: #include <iostream>

#include <vector>
#include <queue>
#include <climits>

using namespace std;

#define INF INT_MAX

typedef pair<int, int> pii;

void dijkstra(vector<vector<pii>>& graph, int start) {


int n = graph.size();
vector<int> dist(n, INF);
dist[start] = 0;

priority_queue<pii, vector<pii>, greater<pii>> pq;


pq.push({0, start});

while (!pq.empty()) {
int u = pq.top().second;
int d = pq.top().first;
pq.pop();

if (d > dist[u]) continue;


for (auto& edge : graph[u]) {
int v = edge.first;
int w = edge.second;

if (dist[u] + w < dist[v]) {


dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}

for (int i = 0; i < n; ++i) {


cout << "Distance from node " << start << " to node " << i << " is: " << dist[i] << endl;
}
}

int main() {
int n = 6; // Number of nodes
vector<vector<pii>> graph(n);

// Adding edges to the graph


graph[0].push_back({1, 5});
graph[0].push_back({2, 3});
graph[1].push_back({3, 6});
graph[1].push_back({4, 2});
graph[2].push_back({3, 7});
graph[2].push_back({5, 3});
graph[3].push_back({4, 1});
graph[3].push_back({5, 5});
graph[4].push_back({5, 7});

dijkstra(graph, 0);

return 0;
}

[03-01, 11:19 a.m.] 💔: Hashtable

[03-01, 11:19 a.m.] 💔: #include <iostream>

#include <vector>

class HashTable {
private:
static const int TABLE_SIZE = 10;
std::vector<std::pair<int, std::string>> table[TABLE_SIZE];

int hashFunction(int key) {


return key % TABLE_SIZE;
}

public:
void insert(int key, const std::string& value) {
int index = hashFunction(key);
table[index].push_back(std::make_pair(key, value));
}

void remove(int key) {


int index = hashFunction(key);
for (auto it = table[index].begin(); it != table[index].end(); ++it) {
if (it->first == key) {
table[index].erase(it);
break;
}
}
}

std::string search(int key) {


int index = hashFunction(key);
for (const auto& entry : table[index]) {
if (entry.first == key) {
return entry.second;
}
}
return "Key not found";
}
};

int main() {
HashTable ht;

ht.insert(5, "Apple");
ht.insert(15, "Banana");
ht.insert(25, "Cherry");

std::cout << ht.search(15) << std::endl;

ht.remove(15);

std::cout << ht.search(15) << std::endl;

return 0;
}

[03-01, 11:20 a.m.] 💔: Chaining

[03-01, 11:20 a.m.] 💔: #include <iostream>

class Chain {
public:
Chain(int value) : value(value) {}

Chain& add(int num) {


value += num;
return *this;
}

Chain& subtract(int num) {


value -= num;
return *this;
}

void print() {
std::cout << "Current value: " << value << std::endl;
}

private:
int value;
};

int main() {
Chain chain(10);
chain.add(5).subtract(3).add(10).subtract(2).print();

return 0;
}

[03-01, 11:21 a.m.] 💔: Backtracking

[03-01, 11:21 a.m.] 💔: #include <iostream>

const int N = 8;
int solution[N];

void backtracking(int step) {


if (step == N) {
for (int i = 0; i < N; ++i) {
std::cout << solution[i] << " ";
}
std::cout << std::endl;
return;
}

for (int i = 1; i <= N; ++i) {


bool valid = true;
for (int j = 0; j < step; ++j) {
if (solution[j] == i) {
valid = false;
break;
}
}
if (valid) {
solution[step] = i;
backtracking(step + 1);
}
}
}

int main() {
backtracking(0);
return 0;
}

[03-01, 11:24 a.m.] 💔: Min recursive

[03-01, 11:24 a.m.] 💔: #include <iostream>


int findMin(int arr[], int n) {
if (n == 1)
return arr[0];
return std::min(arr[n-1], findMin(arr, n-1));
}

int main() {
int arr[] = {12, 4, 7, 9, 2, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int minVal = findMin(arr, n);
std::cout << "Minimum value in the array: " << minVal << std::endl;
return 0;
}

[03-01, 11:25 a.m.] 💔: Nonrecursive

[03-01, 11:25 a.m.] 💔: #include <iostream>

int findMax(int arr[], int size) {


if (size == 0) {
return INT_MIN;
}

int maxVal = arr[0];


for (int i = 1; i < size; ++i) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}

return maxVal;
}

int main() {
int arr[] = {10, 30, 20, 50, 40};
int size = sizeof(arr) / sizeof(arr[0]);
int maxElement = findMax(arr, size);

std::cout << "The maximum element in the array is: " << maxElement << std::endl;

return 0;
}

[03-01, 11:25 a.m.] 💔: Delete leaf in BSTs

[03-01, 11:27 a.m.] 💔: Node* deleteNode(Node* root, int key) {

if (root == NULL) return root;


if (key < root->data)
root->left = deleteNode(root->left, key);
else if (key > root->data)
root->right = deleteNode(root->right, key);
else {
if (root->left == NULL) {
Node* temp = root->right;
delete root;
return temp;
} else if (root->right == NULL) {
Node* temp = root->left;
delete root;
return temp;
}
Node* temp = minValueNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}

[03-01, 11:31 a.m.] 💔: Tower hanoi

[03-01, 11:31 a.m.] 💔: #include <iostream>

void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) {


if (n == 1) {
std::cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod << std::endl;
return;
}
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
std::cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod <<
std::endl;
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}
int main() {
int n = 3; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B, and C are the rod names
return 0;
}

[03-01, 11:31 a.m.] 💔: #include <iostream>

void selectionSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
std::cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
return 0;
}

[03-01, 11:32 a.m.] 💔: Sorting technique

You might also like