c++在二叉排序树中查找指定的关键字,并在查找过程中输出查找过程中历经的节点
时间: 2024-02-01 12:17:01 浏览: 66
好的,你可以参考以下代码实现:
```cpp
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};
void searchBST(TreeNode* root, int key) {
if (!root) return;
if (root->val == key) {
cout << "Found key " << key << endl;
return;
}
else if (root->val > key) {
cout << "Node " << root->val << " is visited." << endl;
searchBST(root->left, key);
}
else {
cout << "Node " << root->val << " is visited." << endl;
searchBST(root->right, key);
}
}
int main() {
// 构建一棵二叉排序树
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(8);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(10);
// 查找关键字为 4 的节点
searchBST(root, 4);
// 释放内存
delete root->left->left;
delete root->left->right;
delete root->left;
delete root->right->left;
delete root->right->right;
delete root->right;
delete root;
return 0;
}
```
运行结果:
```
Node 5 is visited.
Node 3 is visited.
Node 4 is visited.
Found key 4
```
在查找过程中,每经过一个节点就会输出该节点的值,直到找到目标节点或者遍历完整棵树。
阅读全文