二叉链表的查找代码,用c++语言实现
时间: 2024-04-11 18:28:58 浏览: 72
以下是用C++语言实现二叉链表查找的代码示例:
```cpp
#include <iostream>
struct Node {
int data;
Node* left;
Node* right;
};
// 在二叉树中查找特定值的节点
Node* searchNode(Node* root, int value) {
if (root == nullptr || root->data == value) {
return root;
}
// 递归地在左子树中查找
Node* leftResult = searchNode(root->left, value);
if (leftResult != nullptr) {
return leftResult;
}
// 递归地在右子树中查找
Node* rightResult = searchNode(root->right, value);
return rightResult;
}
int main() {
// 创建二叉链表
Node* root = new Node();
root->data = 4;
Node* node1 = new Node();
node1->data = 2;
Node* node2 = new Node();
node2->data = 6;
Node* node3 = new Node();
node3->data = 1;
Node* node4 = new Node();
node4->data = 3;
Node* node5 = new Node();
node5->data = 5;
Node* node6 = new Node();
node6->data = 7;
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = node4;
node2->left = node5;
node2->right = node6;
// 查找节点值为5的节点
Node* result = searchNode(root, 5);
if (result != nullptr) {
std::cout << "找到了节点值为5的节点!" << std::endl;
} else {
std::cout << "未找到节点值为5的节点!" << std::endl;
}
// 释放内存
delete root;
delete node1;
delete node2;
delete node3;
delete node4;
delete node5;
delete node6;
return 0;
}
```
这段代码首先定义了一个二叉树的节点结构体`Node`,包含一个整数数据`data`以及左右子节点的指针`left`和`right`。然后实现了一个名为`searchNode`的递归函数,用于在二叉树中查找特定值的节点。在`main`函数中,创建了一个二叉链表,并调用`searchNode`函数查找节点值为5的节点。最后释放了申请的内存空间。
阅读全文