以c语言为基础帮我写一个能够实现各种遍历的二叉树代码,需要有左右结点的插入区别
时间: 2024-05-09 08:21:56 浏览: 17
好的,我可以为您提供一个基于C语言的二叉树遍历代码,其中包含了左右结点的插入区别。具体代码如下(注:代码仅供参考,可能需要根据实际需求进行修改):
```
#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建一棵新的二叉树节点
TreeNode* createNode(int val) {
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 插入左结点
void insertLeft(TreeNode *root, int val) {
TreeNode *node = createNode(val);
root->left = node;
}
// 插入右结点
void insertRight(TreeNode *root, int val) {
TreeNode *node = createNode(val);
root->right = node;
}
// 先序遍历
void preorder(TreeNode *root) {
if(root != NULL) {
printf("%d ", root->val);
preorder(root->left);
preorder(root->right);
}
}
// 中序遍历
void inorder(TreeNode *root) {
if(root != NULL) {
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
}
// 后序遍历
void postorder(TreeNode *root) {
if(root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->val);
}
}
int main() {
TreeNode *root = createNode(1);
insertLeft(root, 2);
insertRight(root, 3);
insertLeft(root->left, 4);
insertRight(root->left, 5);
printf("先序遍历:");
preorder(root);
printf("\n");
printf("中序遍历:");
inorder(root);
printf("\n");
printf("后序遍历:");
postorder(root);
printf("\n");
return 0;
}
```
在上面的代码中,我们首先定义了一个名为 TreeNode 的结构体,其中包含了值 val、左子节点 left 和右子节点 right。接着,我们定义了 createNode() 函数来创建新的二叉树节点,并且实现了 insertLeft() 和 insertRight() 这两个函数来分别插入左结点和右结点。
最后,我们使用了先序遍历、中序遍历和后序遍历这三种方式来遍历二叉树的所有节点,并且通过 insertLeft() 和 insertRight() 函数来创建左右结点的区别。