【问题标题】:Binary search tree doesn't work二叉搜索树不起作用
【发布时间】:2011-09-28 08:55:24
【问题描述】:

我在构建二叉树时遇到了一个非常令人困惑的问题。显然这应该是一项简单的任务,但不知何故我可能会弄乱其中的指针。

这是简化的代码(当然不是真正的代码):

#include <string.h>
#include <iostream>

using namespace std;

#define DIM1 2 

typedef enum {LEFT,RIGHT} direction;
typedef char tName[MAX_NAME_LEN + 1];

struct Rectangle {
  tName _name; 
  struct Rectangle *_binSon[DIM1];             
};

struct Rectangle *recTree;

void insertRectToTree(char str[]){  
    struct Rectangle rect;
    struct Rectangle *point;
    struct Rectangle *parent;
    strcpy(rect._name,str);
    rect._binSon[RIGHT] = NULL;
    rect._binSon[LEFT] = NULL;
    point = &rect;
    if (recTree == NULL){
       recTree = point;
    } else {
      struct Rectangle *current;
      current = recTree;
      while (current){
          parent = current;
          if (strcmp(point -> _name, current -> _name) > 0){
              current = current -> _binSon[RIGHT];
          } else {
              current = current -> _binSon[LEFT];
          }
      }
      if (strcmp(point -> _name, parent -> _name) < 0){
          parent -> _binSon[LEFT] = point;
      } else {
          parent -> _binSon[RIGHT] = point;
      }
      }
   }

int main(){
   recTree = NULL;
   char str[] = "LIKE";
   insertRectToTree(str);
   char str2[] = "GUIDE";
   insertRectToTree(str2);
   printf(recTree -> _name);
   return 0;
}

如您所见,这棵二叉树会尝试根据其名称来组织记录,因此最小的字母顺序会排在左侧,依此类推。

问题是,在第一次插入“LIKE”之后,我希望将“GUIDE”也插入到树中,而“LIKE”仍然作为根。但是,printf() 显示“GUIDE”作为其根。 (换句话说,“GUIDE”是输出)。对此有什么好的解释吗?问我是否需要为这个问题添加更多内容。感谢您所有的帮助。

【问题讨论】:

  • 它是 c++,但我敢打赌它也适用于 c,因为我不使用任何类
  • 为什么要把关键字struct放在"struct Rectangle *current;"这一行里
  • 是的,我想我需要摆脱那些。但是还是不能解决问题,唉

标签: c++ binary-tree


【解决方案1】:

以下几行

struct Rectangle rect;
...
point = &rect;
...
recTree = point;

您将对局部变量的引用分配给全局指针。离开函数后,它可能不再包含有效数据。

【讨论】:

  • 确实如此。你有什么解决方法吗?老实说,我有点讨厌指针
  • @vandershraaf 使用point = new struct Rectangle; 和后来的point -&gt; _binSon[RIGHT] = NULL; ... 并完全摆脱rect
  • 我没有使用 [new struct Rectangle] 而是使用 [new Rectangle]。顺便说一句,感谢您的回复。这是最好的答案,因为我之前不知道真正的问题
【解决方案2】:

霍华德是正确的。但要纠正问题,请使用 new。

即代替 point = &amp;rect;

point = new struct Rectangle;

【讨论】:

  • 我试过这个,但它有错误。还有其他解决方法吗?
  • 我已经尝试过了,但 [point = new Rectangle] 效果更好。尽管如此,我还是要为你的见解投赞成票
猜你喜欢
  • 2020-09-29
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2011-05-24
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多