【问题标题】:How to read in .txt file line by line to binary search tree如何逐行读取.txt文件到二叉搜索树
【发布时间】:2015-12-03 16:55:46
【问题描述】:

我正在尝试创建一个二叉搜索树并逐行读取文本文件作为每一行的节点,例如:

Dave Smith 0728492940
Ed James 0956294587

这样我就可以让用户输入一个名字“Dave”,它会显示他们的全名和电话号码。我只是不确定如何实现将文本文件逐行读取到二叉搜索树中,以便为每一行创建一个节点。目前我只是打印出文本文件而不将其放入 BST。 到目前为止的代码如下:

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node* left;
    struct node* right;
} ;

//tree wrapper structure
struct tree {
    struct node *root;
} ;

typedef struct tree Tree;
typedef struct node Node;

//create a new tree
Tree *new_tree() {
    Tree *t = malloc(sizeof(Tree));
    t->root = NULL;
    return t;
}

//create a new node
Node* NewNode(int data) {
  Node* node = malloc(sizeof *node);
  node->data = data;
  node->left = NULL;
  node->right = NULL;

  return(node);
}
//insert in to the binary tree
Node* insert(Node* node, char *data) {
  // 1. If the tree is empty, return a new, single node
  if (node == NULL) {
    return(NewNode(*data));
  }
  else {
    // 2. Otherwise, recur down the tree
    if (*data <= node->data) node->left = insert(node->left, data);
    else node->right = insert(node->right, data);

    return(node); // return the (unchanged) node pointer
  }
}
//search for nodes to see if they exist
bool NodeSearch(Node* node,int data) {
    if(node==NULL) return false;
    else if(node->data == data) return true;
    else if(data  <= node ->data) return NodeSearch(node->left, data);
    else return NodeSearch(node->right, data);
}

int main(){

    FILE *f;
    char s[1000];

    f=fopen("phone.txt", "r");
    if(!f)
        return 1;
    while (fgets(s,1000,f)!=NULL) {
        printf("%s\n", s);
    }
    fclose(f);
    return 0;
}

【问题讨论】:

  • 如果您想搜索名字、姓氏或电话号码(顺便说一下,不要将它们存储为整数,这会使您失去初始零),那么您实际上需要 three 树:一棵以名字为键,第二棵以姓为键,第三棵以电话号码为键。好处是您可以对所有树使用相同的结构和功能。哦,您绝对应该阅读更多关于 self-balancing binary search trees 的信息。
  • 您的结构定义了您的树将保存哪些数据。目前它持有int data;。您需要更改它以保存您需要存储的类型数据(例如 first namelast namenumber)。在您的while (fgets(s,1000,f)!=NULL) 循环中,您需要将行解析为要存储在每个节点中的数据,然后调用 insert node 将节点添加到树中。我尚未验证您的树代码,但您需要先阅读/解析s 中的数据。
  • 您能否更具体地说明您希望如何执行部分名称匹配?在 BST 中,您通常使用完整密钥进行搜索,因此您的特定要求对于答案很重要。例如,匹配包含在您的键中某处的子字符串是仅匹配前缀的另一项任务,如果您想允许拼写错误等,则仍然是另一项任务......
  • @BeyelerStudios 我不想考虑错别字或任何东西,只要用户输入一个单词,例如"smith" 然后它会打印包含该单词的所有节点。
  • 那么 BST 不是合适的工具,查找 suffix tree

标签: c binary-search-tree


【解决方案1】:

如果用户输入一个单词,例如"smith" 然后打印所有节点 包含那个词。

如果您需要在(部分)键中搜索,则使用二叉搜索树是没有意义的;你也可以使用一个简单的数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多