写出C语言代码在二叉树查找是否存在值为x的结点
时间: 2023-06-10 16:04:01 浏览: 49
当然,我可以为你提供代码。请看下面:
```
#include <stdio.h>
#include <stdlib.h>
struct node
{
int key;
struct node *left, *right;
};
// 创建新节点并返回
struct node* newNode(int item)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// 二叉树查找
struct node* search(struct node* root, int key)
{
if (root == NULL || root->key == key)
return root;
if (root->key < key)
return search(root->right, key);
return search(root->left, key);
}
// 插入节点
struct node* insert(struct node* node, int key)
{
if (node == NULL) return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
// 打印中序遍历结果
void inorder(struct node* root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
// 主程序
int main()
{
struct node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
printf("中序遍历结果:\n");
inorder(root);
printf("\n");
int x = 40;
struct node* result = search(root, x);
if(result)
{
printf("%d存在于二叉树中\n", x);
}
else
{
printf("%d不在二叉树中\n", x);
}
return 0;
}
```
这个代码基本上是一个二叉查找树的模板,它能够插入节点、进行中序遍历、查找特定节点。你可以将其中的节点值改为自己想要查找的值,修改一下就可以使用了。