Untitled
irfann
plain_text
2 years ago
2.5 kB
3
Indexable
#include <stdio.h> #include <stdlib.h> // Define structures for Node, Tree, and Graph typedef struct Node { int data; struct Node* next; } Node; typedef struct Tree { int data; struct Tree* left; struct Tree* right; } Tree; typedef struct Graph { int data; struct Graph* next; } Graph; // Function to create and initialize an empty Tree Tree* createTree(int data) { Tree* newNode = (Tree*)malloc(sizeof(Tree)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } // Function to create and initialize an empty Graph Graph* createGraph(int data) { Graph* newNode = (Graph*)malloc(sizeof(Graph)); newNode->data = data; newNode->next = NULL; return newNode; } // Function to insert a new node into the Tree Tree* insertTree(Tree* root, int data) { if (root == NULL) { return createTree(data); } else if (data < root->data) { root->left = insertTree(root->left, data); } else { root->right = insertTree(root->right, data); } return root; } // Function to insert a new node into the Graph void insertGraph(Graph* vertices[], int source, int destination) { Graph* newNode = createGraph(destination); newNode->next = vertices[source]; vertices[source] = newNode; } // Function to display the Tree using in-order traversal void inOrderTraversal(Tree* root) { if (root != NULL) { inOrderTraversal(root->left); printf("%d ", root->data); inOrderTraversal(root->right); } } // Function to display the Graph void displayGraph(Graph* vertices[], int n) { printf("Graph:\n"); for (int i = 0; i < n; i++) { printf("Node %d: ", i); Graph* temp = vertices[i]; while (temp != NULL) { printf("%d -> ", temp->data); temp = temp->next; } printf("NULL\n"); } } int main() { Tree* tree = NULL; Graph* graph[5]; // Assuming 5 nodes in the graph for (int i = 0; i < 5; i++) { graph[i] = NULL; } // Sample Tree insertion tree = insertTree(tree, 50); tree = insertTree(tree, 30); tree = insertTree(tree, 70); tree = insertTree(tree, 20); tree = insertTree(tree, 40); // Sample Graph insertion insertGraph(graph, 0, 1); insertGraph(graph, 0, 4); insertGraph(graph, 1, 2); insertGraph(graph, 1, 3); insertGraph(graph, 1, 4); insertGraph(graph, 2, 3); insertGraph(graph, 3, 4); printf("In-order Traversal of Tree: "); inOrderTraversal(tree); printf("\n"); displayGraph(graph, 5); return 0; }
Editor is loading...
Leave a Comment