用c++写一个二叉树检索算法
时间: 2024-05-08 10:15:54 浏览: 13
以下是一个基本的二叉树检索算法的C实现:
```
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结点
typedef struct Node {
int data;
struct Node *left;
struct Node *right;
} Node;
// 创建新结点
Node* createNode(int data) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// 插入结点
Node* insertNode(Node* node, int data) {
if (node == NULL) {
return createNode(data);
} else if (data <= node->data) {
node->left = insertNode(node->left, data);
} else {
node->right = insertNode(node->right, data);
}
return node;
}
// 查找结点
Node* search(Node* node, int data) {
if (node == NULL || node->data == data) {
return node;
} else if (data < node->data) {
return search(node->left, data);
} else {
return search(node->right, data);
}
}
// 主函数
int main() {
Node* root = NULL;
root = insertNode(root, 10);
root = insertNode(root, 6);
root = insertNode(root, 15);
root = insertNode(root, 3);
root = insertNode(root, 8);
root = insertNode(root, 12);
root = insertNode(root, 18);
Node* result = search(root, 8);
if (result == NULL) {
printf("Element not found\n");
} else {
printf("Element found: %d\n", result->data);
}
result = search(root, 20);
if (result == NULL) {
printf("Element not found\n");
} else {
printf("Element found: %d\n", result->data);
}
return 0;
}
```
在此实现中,我们首先定义了二叉树结点,然后创建了一个用于创建新结点的函数。接下来,我们实现了一个用于插入结点的函数,该函数根据数据值将结点插入到树的正确位置。最后,我们实现了一个用于查找结点的函数,该函数使用递归算法在树中查找目标结点。在主函数中,我们创建了一个简单的二叉树,并使用search函数在树中查找两个不同的数据值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)