Binary Tree in C: Recursive Implementation Guide
In the C language, binary trees can be created using structures and recursive functions. Below is a simple example code:
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树的节点结构体
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// 递归生成二叉树
Node* createBinaryTree() {
int data;
Node* root = NULL;
printf("输入节点的值(-1表示空节点):");
scanf("%d", &data);
if (data == -1) {
return NULL;
}
root = createNode(data);
printf("输入%d的左子节点:\n", data);
root->left = createBinaryTree();
printf("输入%d的右子节点:\n", data);
root->right = createBinaryTree();
return root;
}
// 测试函数
void preorderTraversal(Node* root) {
if (root != NULL) {
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
int main() {
Node* root = createBinaryTree();
printf("前序遍历结果:\n");
preorderTraversal(root);
return 0;
}
In the code above, we first defined a node structure called Node, then created a function createNode to create new nodes. Next, we used a recursive function createBinaryTree to generate a binary tree where users can input node values, with -1 representing empty nodes. Finally, we output the generated binary tree using the preorderTraversal function.
You can run this code, enter the values of nodes as prompted to generate a binary tree, and output the result of pre-order traversal.