在二叉排序树中查找指定的关键字,并在查找过程中输出查找过程中历经的节点 代码
时间: 2023-07-15 14:14:56 浏览: 92
二叉排序树(一个关键字)
以下是在二叉排序树中查找指定关键字并输出查找过程中历经的节点的代码:
```c++
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* searchBST(TreeNode* root, int val) {
if (root == NULL || root->val == val) {
return root;
}
if (val < root->val) {
cout << root->val << " -> "; // 输出经过的节点
return searchBST(root->left, val);
} else {
cout << root->val << " -> "; // 输出经过的节点
return searchBST(root->right, val);
}
}
int main() {
TreeNode* root = new TreeNode(4);
root->left = new TreeNode(2);
root->right = new TreeNode(6);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(3);
root->right->left = new TreeNode(5);
root->right->right = new TreeNode(7);
int val = 5;
TreeNode* result = searchBST(root, val);
if (result == NULL) {
cout << "The value " << val << " is not found in the BST." << endl;
} else {
cout << "The value " << val << " is found in the BST." << endl;
}
return 0;
}
```
上述代码中,`searchBST` 函数用于在二叉排序树中查找指定关键字,并输出查找过程中历经的节点。如果找到了指定的关键字,则返回该节点;否则返回 NULL。`main` 函数创建了一个二叉排序树,并调用 `searchBST` 函数查找指定的关键字。如果找到了指定的关键字,输出 "The value [val] is found in the BST.";否则输出 "The value [val] is not found in the BST."。
阅读全文