Trees and Graphs in C - A Basic Overview


Introduction

Trees and graphs are complex data structures used in computer science and C programming for organizing and representing hierarchical and interconnected data. In this guide, we'll provide a basic overview of trees and graphs, including key concepts and terminology. While the code examples here are simplified, they introduce the fundamental ideas behind these structures.


Trees

A tree is a hierarchical data structure that consists of nodes connected by edges. Each node has a parent node (except for the root node) and zero or more child nodes. Key concepts in trees include the root, parent, child, leaf, and levels.


Sample Code for a Simple Binary Tree

#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int main() {
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Sample Binary Tree Created.\\n");
return 0;
}

Graphs

A graph is a collection of nodes (vertices) connected by edges. Graphs can be used to represent complex relationships and can be either directed (edges have a direction) or undirected. Graphs can be cyclic or acyclic, and they support various traversal and search algorithms.


Sample Code for a Simple Graph

#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 5
struct Graph {
int vertices;
int** adjacencyMatrix;
};
struct Graph* createGraph(int numVertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->vertices = numVertices;
graph->adjacencyMatrix = (int**)malloc(numVertices * sizeof(int*));
for (int i = 0; i < numVertices; i++) {
graph->adjacencyMatrix[i] = (int*)malloc(numVertices * sizeof(int));
for (int j = 0; j < numVertices; j++) {
graph->adjacencyMatrix[i][j] = 0;
}
}
return graph;
}
int main() {
struct Graph* graph = createGraph(MAX_VERTICES);
printf("Sample Graph Created.\\n");
return 0;
}

Conclusion

Trees and graphs are fundamental data structures in C programming, each with its own set of characteristics and use cases. This guide provided a basic overview of trees and graphs, and it introduced key terminology. As you continue your C programming journey, you'll discover more advanced applications and algorithms for these structures, enabling you to solve complex problems and create sophisticated software.