c++ - 如何打印在二叉搜索树中找到的数据?
问题描述
我正在做这个程序,它读取一个 CSV 文件并将其输入到树中,直到现在我已经设法创建树并按顺序显示它们,但是在搜索时我失败了,因为它没有显示信息正在搜索的元素,有人可以帮助我纠正错误,谢谢....
csv 文件包含数据(包含几个,但我将这些作为示例。):
1,name1,number1
2,name2,number2
3,name3,number3
#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
#include <utility>
#include <experimental/optional>
intmax_t dato;
struct Person {
intmax_t key;
std::string name;
intmax_t num;
};
struct Node : Person {
Node(const Person &person) : Person(person) {}
std::unique_ptr<Node> left, right;
void insert(const Person &person);
};
void Node::insert(const Person &person) {
/* recur down the tree */
if (key > person.key) {
if (left)
left->insert(person);
else
left = std::make_unique<Node>(person);
} else if (key < person.key) {
if (right)
right->insert(person);
else
right = std::make_unique<Node>(person);
}
}
std::vector<Person> persons;
void inorder(Node *root) {
if (root) {
// cout<<"\t";
inorder(root->left.get());
std::cout << "\tID: "<< root->key << "\tName: "<< root->name << "\t\tNum: " << root->num << '\n'; //'\t' ' '
inorder(root->right.get());
}
}
std::experimental::optional<Person> busqueda(Node *root, intmax_t dato) {
if(root==NULL){
return {};
}
else if(root->key==dato){
return *root;
}
else if(dato<root->key){
return busqueda(root->left.get(),dato);
}
else{
return busqueda(root->right.get(),dato);
}
}
int main() {
std::unique_ptr<Node> root;
std::ifstream fin("data.txt");
if (!fin) {
std::cout << "File not open\n";
return 1;
}
std::string line;
const char delim = ',';
std::cout<<"\t\tData\n"<<std::endl;
while (std::getline(fin, line)) {
std::istringstream ss(line);
Person person;
ss >> person.key;
ss.ignore(10, delim);
std::getline(ss, person.name, delim);
ss >> person.num;
if (ss) persons.push_back(person);
}
for (unsigned int i = 0; i < persons.size(); i++) {
std::cout << std::setw(10)<<"ID: " << persons[i].key << std::setw(30)<<"Name: "
<< persons[i].name << std::setw(20) <<"Num: "<< persons[i].num << '\n';
if (!root) root = std::make_unique<Node>(persons[i]);
else root->insert(persons[i]);
}
std::cout << "\n\n\t\tInorder:\n\n";
inorder(root.get());
std::cout<<" Enter data: "; std::cin>> dato;
busqueda(root.get(),dato);
if(busqueda(root.get(),dato)){
std::cout<<"Data found"<<std::endl;
std::cout<<root->name;//does not show the wanted, only the first of the document.
}
else{
std::cout<<"\nData not found"<<std::endl;
}
return 0;
}
解决方案
从您在以下语句中丢弃搜索结果的评论中:
busqueda(root.get(),dato);
返回可选值 std::experimental::optional 但您不使用该值。
您使用测试该值,if(busqueda(root.get(),dato)){
但由于您没有存储结果,因此您第二次搜索并且没有办法获取 Person 对象。
相反,您可以这样做来获取 person 对象并显示其名称:
std::cout << " Enter data: "; std::cin >> dato;
auto result = busqueda(root.get(), dato);
if (result) {
std::cout << "Data found" << std::endl;
std::cout <<result->name; // This should be the name of the found Person
}
else {
std::cout << "\nData not found" << std::endl;
}