如何正确存储指向二叉搜索树根的指针?

时间:2018-08-22 03:17:55

标签: c binary-search-tree

我正在尝试将一系列节点插入二叉搜索树。我设置了以下main和struct。我的问题是,当我在每个节点相加之后打印值parent->name(*insertLocation)->name时,它们包含新节点的数据,而不是我想要的树根。我相信这与以某种方式被重新分配而不保留根值的父指针有关。还有其他保留二叉树根的方法吗?

typedef struct nodeT{
    char* name;
    char** data;
    struct nodeT* left;
    struct nodeT* right;
} node_t ;    

int main(int argc, char** argv){

    node_t *parent = NULL;
    node_t** Location = &parent;

    int i;
    char* name = malloc(sizeof(char)*MAXSTRLEN);
    char** data = malloc(sizeof(char*)*NUMRECORDS);
    for (i = 0; i < NUMRECORDS; i++){
        data[i] = malloc(sizeof(char)*MAXSTRLEN);
    }
    add(Location, data, name);
}

我插入节点的功能如下:

node_t* newNode(char** data, char* name){

  node_t* node = (node_t*) malloc(sizeof(node_t));
  node->data  = data;
  node->name  = name;
  node->left  = NULL;
  node->right = NULL;
  return node;
}

void add(node_t** insertLocation, char** data, char* name){

    node_t* curr = *insertLocation;
    if(curr == NULL){
        curr = newNode(data, name);
        *insertLocation = curr;
    }else{
        if(data[0] < curr->data[0]){
            add(&curr->left, data, name);
        }else{
            add(&curr->right, data, name);
        }
    }
}

0 个答案:

没有答案