c语言实现查找二叉树结点
时间: 2023-10-16 12:10:08 浏览: 43
以下是用C语言实现查找二叉树节点的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};
struct node* insert(struct node *root, int data);
struct node* search(struct node *root, int data);
int main() {
struct node *root = NULL;
int data, choice;
do {
printf("\nEnter choice:\n1. Insert\n2. Search\n3. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to be inserted: ");
scanf("%d", &data);
root = insert(root, data);
break;
case 2:
printf("Enter data to be searched: ");
scanf("%d", &data);
if (search(root, data) == NULL) {
printf("Data not found!\n");
} else {
printf("Data found!\n");
}
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
break;
}
} while (choice != 3);
return 0;
}
struct node* insert(struct node *root, int data) {
if (root == NULL) {
struct node *newNode = (struct node*) malloc(sizeof(struct node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
} else if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
struct node* search(struct node *root, int data) {
if (root == NULL || root->data == data) {
return root;
} else if (data < root->data) {
return search(root->left, data);
} else {
return search(root->right, data);
}
}
```
在以上代码中,我们定义了一个简单的二叉树节点结构体,包含了数据、左子节点和右子节点。我们实现了插入节点和查找节点的函数,其中插入函数使用递归实现,查找函数也使用了递归来遍历二叉树。
在主函数中,我们使用一个循环来提供用户菜单选项,包括插入数据、查找数据和退出程序。在插入和查找时,我们调用相应的函数来执行操作。