#include <stdio.h>
#include <stdlib.h>
// Simple tree node
typedef struct TreeNode {
char val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// Simple graph node with adjacency list
typedef struct GraphNode {
char val;
struct GraphNode** neighbors;
int neighborCount;
} GraphNode;
// Create tree node
TreeNode* createTreeNode(char val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// Create graph node
GraphNode* createGraphNode(char val) {
GraphNode* node = (GraphNode*)malloc(sizeof(GraphNode));
node->val = val;
node->neighbors = NULL;
node->neighborCount = 0;
return node;
}
// Add neighbor to graph node
void addNeighbor(GraphNode* node, GraphNode* neighbor) {
node->neighborCount++;
node->neighbors = (GraphNode**)realloc(node->neighbors, node->neighborCount * sizeof(GraphNode*));
node->neighbors[node->neighborCount - 1] = neighbor;
}
// Print tree (preorder)
void printTree(TreeNode* root) {
if (!root) return;
printf("%c ", root->val);
printTree(root->left);
printTree(root->right);
}
// Print graph adjacency
void printGraph(GraphNode** nodes, int count) {
for (int i = 0; i < count; i++) {
printf("%c: ", nodes[i]->val);
for (int j = 0; j < nodes[i]->neighborCount; j++) {
printf("%c ", nodes[i]->neighbors[j]->val);
}
printf("\n");
}
}
int main() {
// Build tree: A -> B, C
TreeNode* A = createTreeNode('A');
TreeNode* B = createTreeNode('B');
TreeNode* C = createTreeNode('C');
A->left = B;
A->right = C;
printf("Tree (preorder): ");
printTree(A);
printf("\n");
// Build graph: A-B, A-C, B-D, C-D
GraphNode* GA = createGraphNode('A');
GraphNode* GB = createGraphNode('B');
GraphNode* GC = createGraphNode('C');
GraphNode* GD = createGraphNode('D');
addNeighbor(GA, GB);
addNeighbor(GA, GC);
addNeighbor(GB, GD);
addNeighbor(GC, GD);
GraphNode* graphNodes[] = {GA, GB, GC, GD};
printf("Graph adjacency:\n");
printGraph(graphNodes, 4);
return 0;
}
A->left = B;
A->right = C;
Set left and right children to build tree structure
addNeighbor(GA, GB);
addNeighbor(GA, GC);
addNeighbor(GB, GD);
addNeighbor(GC, GD);
Add edges to graph nodes to build multiple connections
Tree (preorder): A B C
Graph adjacency:
A: B C
B: D
C: D
D: