用c语言写一段二叉树交互节点
时间: 2023-04-06 20:03:39 浏览: 96
很高兴回答你的问题。以下是用 C 语言编写的二叉树交互节点的代码:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *createNode(int data) {
struct node *newNode = (struct node*) malloc(sizeof(struct node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct node *insert(struct node *root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else {
root->right = insert(root->right, data);
}
return root;
}
void inorderTraversal(struct node *root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}
int main() {
struct node *root = NULL;
int choice, data;
do {
printf("\n1. Insert a node");
printf("\n2. Inorder traversal");
printf("\n3. Exit");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter data to be inserted: ");
scanf("%d", &data);
root = insert(root, data);
break;
case 2:
printf("\nInorder traversal: ");
inorderTraversal(root);
break;
case 3:
printf("\nExiting...");
exit(0);
default:
printf("\nInvalid choice!");
}
} while (choice != 3);
return 0;
}
```
这段代码实现了二叉树的插入和中序遍历功能,用户可以通过菜单选择插入节点或者中序遍历二叉树。希望这个代码对你有所帮助!
阅读全文