开发者

Binary search tree doesn't work

开发者 https://www.devze.com 2023-04-08 18:43 出处:网络
I\'m having a pretty confusing problem in building a binary tree. Apparently this should be an easy task but somehow I may mess up with the pointers in it.

I'm having a pretty confusing problem in building a binary tree. Apparently this should be an easy task but somehow I may mess up with the pointers in it.

Here's the simplified code (of course it's not the real code) :

#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;
    str开发者_运维百科uct 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;
}

As you can see, this binary tree tries to organize a record based on its name, so the smallest alphabetical order will go to the left side and so on.

The problem is, after the first insertion "LIKE", I want "GUIDE" inserted to the tree as well, with "LIKE" still as the root. However, the printf() shows that "GUIDE" takes over as its root. (In other word, "GUIDE" is the output). Any good explanation for this? Ask me if I need to add some more thing to this question. Thanks for all of your help.


Within the following lines

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

you assign a reference to a local variable to a global pointer. After leaving the function it may no longer contain valid data.


Howard is correct. But to correct the problem use new.

i.e. instead of point = &rect;

Put point = new struct Rectangle;

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号