c语言二叉树的基本操作,请用代码展示
时间: 2023-05-18 12:04:21 浏览: 94
C语言二叉树基本操作
以下是 C 语言二叉树的基本操作代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *create_node(int data) {
struct node *new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
struct node *insert_node(struct node *root, int data) {
if (root == NULL) {
return create_node(data);
}
if (data < root->data) {
root->left = insert_node(root->left, data);
} else if (data > root->data) {
root->right = insert_node(root->right, data);
}
return root;
}
struct node *search_node(struct node *root, int data) {
if (root == NULL || root->data == data) {
return root;
}
if (data < root->data) {
return search_node(root->left, data);
} else {
return search_node(root->right, data);
}
}
void inorder_traversal(struct node *root) {
if (root != NULL) {
inorder_traversal(root->left);
printf("%d ", root->data);
inorder_traversal(root->right);
}
}
int main() {
struct node *root = NULL;
root = insert_node(root, 50);
insert_node(root, 30);
insert_node(root, 20);
insert_node(root, 40);
insert_node(root, 70);
insert_node(root, 60);
insert_node(root, 80);
printf("Inorder traversal of the binary search tree: ");
inorder_traversal(root);
printf("\n");
return 0;
}
```
以上代码实现了二叉树的基本操作,包括创建节点、插入节点、查找节点和中序遍历。在主函数中,我们创建了一个二叉搜索树,并对其进行了中序遍历。
阅读全文