#include <stdio.h>
#include <stdlib.h>
// 定义三叉树节点结构体
typedef struct TripletNode {
int data;
struct TripletNode *left;
struct TripletNode *middle;
struct TripletNode *right;
} TripletNode;
// 创建新的三叉树节点
TripletNode* createNode(int data) {
TripletNode* newNode = (TripletNode*)malloc(sizeof(TripletNode));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(0);
}
newNode->data = data;
newNode->left = NULL;
newNode->middle = NULL;
newNode->right = NULL;
return newNode;
}
// 插入节点到三叉树
void insertNode(TripletNode** root, int data) {
if (*root == NULL) {
*root = createNode(data);
return;
}
TripletNode* current = *root;
TripletNode* parent = NULL;
while (current != NULL) {
parent = current;
if (data < current->data) {
current = current->left;
} else if (data > current->data) {
current = current->right;
} else {
// 节点已存在,不需要插入
return;
}
}
current = createNode(data);
if (data < parent->data) {
parent->left = current;
} else {
parent->right = current;
}
}
// 中序遍历三叉树
void inorderTraversal(TripletNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
int main() {
TripletNode* root = NULL;
// 插入节点
insertNode(&root, 10);
insertNode(&root, 15);
insertNode(&root, 5);
insertNode(&root, 7);
insertNode(&root, 12);
insertNode(&root, 14);
insertNode(&root, 20);
insertNode(&root, 17);
insertNode(&root, 18);
insertNode(&root, 25);
// 中序遍历三叉树
printf("Inorder traversal of the created tree:\n");
inorderTraversal(root);
return 0;
}