c - 有序二叉树中的查找方法

标签 c struct tree

我正在从文本文件中逐行读取,将每一行存储在一个节点中,从而构造一个有序二叉树。

文本文件:

1/12/04 Jones, John $31.11
12/22/03 Dickinson, Tony $5.04
12/15/03 Lee, Jerry $21.12
12/19/03 Kahn, Chris $83.15
1/31/04 Bills, Mike $32.00
1/15/04 Lake, Jeff $6.66

订单与节点关联的金额有关。 (中序遍历将按照金额从最小到最大进行。)

我有一个查找方法,它获取一个节点并在树中搜索它。如果在树中找到,则返回1,否则返回0:

    int lookup(struct treenode *whole, struct treenode *t) {
  if(whole == NULL) 
    return 0;
  else 
    if((whole->year == t->year)&&
       (whole->month == t->month)&&
       (whole->day == t->day)&&
       (whole->lastname == t->lastname)&&
       (whole->firstname == t->firstname)&&
       (whole->money == t->money))
      return 1;
    else 
      if(t->money < whole->money)
    return lookup(whole->left,t);
      else return lookup(whole->right,t);     
}

唯一的问题是,当我创建一个新的单独节点(该节点是树中已有节点的精确副本)时,我的查找方法在应该返回 1 时返回 0。这是树节点结构:

struct treenode { // transaction
  int month,day,year;
  char* lastname;
  char* firstname;
  float money;
  struct treenode *left;
  struct treenode *right;
};

假设 root1 指向一棵树,该树将每一行存储在一个节点中。为什么我的查找方法不起作用?

 if (file1 != NULL) {  
    char line1 [256]; /* or other suitable maximum line size */
    while (fgets(line1, sizeof line1, file1 ) != NULL) {

      sscanf(line1,"%d/%d/%d %s %s $%f", &month, &day, &year, lastname,
         firstname, &money);
      // printf("%d/%d/%d %s %s $%.2f\n", month, day, year, lastname,
      //     firstname, money );
      tr1 = talloc(month, day, year, lastname, firstname, money);
      root1 = addtree(root1, tr1);       
    }
    fclose (file1);
  }
  else {
    perror (filename1); /* why didn't the file open? */
  }
 printf("IN TREE: %d\n",lookup(root1,test));
IN TREE: 0

最佳答案

当该节点与另一个节点相等时,您将该节点放在哪里?向左还是向右?

看起来你的查找函数在找到相等的节点时采取了另一种方式,因为你有钱>和钱<,但不相等。

插入和搜索时需要使用相同的比较,如果等于在右边则使用 = 来表示右边,依此类推。

关于c - 有序二叉树中的查找方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272888/

相关文章:

c - 你如何在 PostgreSQL 中检测 MOVE 的最后一行

c - 将程序返回到主菜单

c# - 将泛型结构转换为具有不同类型参数的相同泛型结构

C 结构体问题

algorithm - 最优搜索树 : Calculate the cost of the search tree and show that it is not optimal

c - 我收到错误消息 : Run-Time Check Failure #2. 变量周围的堆栈已损坏。但是,我没有超出任何数组的范围

c - 为什么 C 编译器很难获得 -Wwrite-strings 警告?

json - 将 Coldfusion json 转换为 struct

algorithm - 二叉树算法第j层中如何取出第i个元素的讨论

当在 C 中接收到 SIGINT 时,在进程树中使用 fork() 创建 X 个子进程