C语言实现二叉树:代码示例和详解
以下是用C语言实现二叉树的示例代码:
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 创建一个新的二叉树节点
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 向二叉树中插入一个节点
struct TreeNode* insertNode(struct TreeNode* root, int val) {
if (root == NULL) {
return createNode(val);
}
if (val < root->val) {
root->left = insertNode(root->left, val);
} else if (val > root->val) {
root->right = insertNode(root->right, val);
}
return root;
}
// 中序遍历二叉树
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf('%d ', root->val);
inorderTraversal(root->right);
}
int main() {
// 创建一个空的二叉树
struct TreeNode* root = NULL;
// 向二叉树中插入节点
root = insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 8);
insertNode(root, 1);
insertNode(root, 6);
insertNode(root, 9);
// 中序遍历二叉树
printf("Inorder traversal of binary tree: ");
inorderTraversal(root);
printf("\n");
return 0;
}
在上述代码中,我们首先定义了一个二叉树的结构体 'TreeNode',其中包含了节点的值以及左右子树的指针。然后我们定义了三个函数:
- 'createNode':用于创建一个新的二叉树节点,并返回该节点的指针。
- 'insertNode':用于向二叉树中插入一个节点,返回插入后的二叉树的根节点。
- 'inorderTraversal':用于中序遍历二叉树,将节点的值按升序输出。
在主函数中,我们首先创建了一个空的二叉树,然后调用 'insertNode' 函数向其中插入六个节点。最后调用 'inorderTraversal' 函数中序遍历二叉树,并将结果输出。
原文地址: https://www.cveoy.top/t/topic/lOw0 著作权归作者所有。请勿转载和采集!