Untitled
unknown
plain_text
23 days ago
2.7 kB
6
Indexable
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int keys[2];
struct Node *children[3];
int numKeys;
} Node;
Node* createNode(int key1, int key2, int numKeys) {
int i;
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->numKeys = numKeys;
newNode->keys[0] = key1;
newNode->keys[1] = key2;
for( i = 0; i < 3; i++)
newNode->children[i] = NULL;
return newNode;
}
int isLeaf(Node *node) {
return node->children[0] == NULL &&
node->children[1] == NULL &&
node->children[2] == NULL;
}
Node* insert(Node *root, int key) {
if (root == NULL)
return createNode(key, 0, 1);
if (isLeaf(root) && root->numKeys == 1) {
if (key < root->keys[0]) {
root->keys[1] = root->keys[0];
root->keys[0] = key;
} else {
root->keys[1] = key;
}
root->numKeys = 2;
return root;
}
if (root->numKeys == 1) {
if (key < root->keys[0])
root->children[0] = insert(root->children[0], key);
else
root->children[1] = insert(root->children[1], key);
}
else {
if (key < root->keys[0])
root->children[0] = insert(root->children[0], key);
else if (key < root->keys[1])
root->children[1] = insert(root->children[1], key);
else
root->children[2] = insert(root->children[2], key);
}
return root;
}
void printNode(Node *node) {
if (node == NULL) return;
if (node->numKeys == 1)
printf("(%d)", node->keys[0]);
else
printf("(%d %d)", node->keys[0], node->keys[1]);
}
void printTreeVisual(Node *root) {
if (root == NULL) return;
printf("\n ");
printNode(root);
printf("\n");
if (root->children[0] || root->children[1] || root->children[2]) {
printf(" / | \\\n");
printf(" ");
if (root->children[0])
printNode(root->children[0]);
printf(" ");
if (root->children[1])
printNode(root->children[1]);
printf(" ");
if (root->children[2])
printNode(root->children[2]);
printf("\n");
}
}
int main() {
int i;
Node *root = NULL;
int n, key;
printf("Enter number of keys: ");
scanf("%d", &n);
printf("Enter keys:\n");
for ( i = 0; i < n; i++) {
scanf("%d", &key);
root = insert(root, key);
}
printf("\nTree Structure:\n");
printTreeVisual(root);
return 0;
}Editor is loading...
Leave a Comment