单词检查二叉排序树实现
时间: 2023-08-21 17:35:23 浏览: 42
单词检查是指对一段文本中出现的单词进行检查,以确定它们是否在一个指定的单词列表中出现过。这个问题可以使用二叉排序树来解决。
二叉排序树是一种有序的二叉树,它满足以下条件:
- 对于二叉树中的每个节点,其左子树中的所有节点的值都小于该节点的值,而右子树中的所有节点的值都大于该节点的值。
- 每个节点都没有重复的值。
我们可以将单词列表中的单词插入到二叉排序树中,并对文本中出现的每个单词进行查找。如果单词存在于二叉排序树中,则说明它出现在单词列表中,否则它不在单词列表中。
下面是一个简单的实现:
```c++
#include <iostream>
#include <string>
using namespace std;
// 二叉排序树节点
struct Node {
string word;
Node* left;
Node* right;
Node(const string& w) : word(w), left(nullptr), right(nullptr) {}
};
// 插入单词到二叉排序树中
Node* insert(Node* root, const string& word) {
if (root == nullptr) {
return new Node(word);
}
if (word < root->word) {
root->left = insert(root->left, word);
} else if (word > root->word) {
root->right = insert(root->right, word);
}
return root;
}
// 在二叉排序树中查找单词
bool search(Node* root, const string& word) {
if (root == nullptr) {
return false;
}
if (word == root->word) {
return true;
} else if (word < root->word) {
return search(root->left, word);
} else {
return search(root->right, word);
}
}
int main() {
// 构建单词列表
string words[] = {"apple", "banana", "cherry", "date", "elderberry"};
Node* root = nullptr;
for (const auto& word : words) {
root = insert(root, word);
}
// 在文本中查找单词
string text = "The apple is a fruit. The banana is also a fruit. The cherry is a kind of berry. The date is a sweet fruit. The elderberry is used to make jam.";
string word;
for (int i = 0; i < text.size(); i++) {
if (isalpha(text[i])) {
word += tolower(text[i]);
} else {
if (!word.empty()) {
if (search(root, word)) {
cout << word << " is in the word list." << endl;
} else {
cout << word << " is not in the word list." << endl;
}
word.clear();
}
}
}
return 0;
}
```
在上面的代码中,我们首先构建了一个单词列表,并将它们插入到二叉排序树中。然后,我们对文本中的每个单词进行查找,如果单词在单词列表中,则输出它在列表中,否则输出它不在列表中。
需要注意的是,在实际应用中,我们可能需要使用更高效的数据结构来存储单词列表,例如散列表。