2011-06-14 130 views
2

我试图实现一个二叉搜索树的目的是(重新)学习C.问题是,这current = new;不工作,因为tree.root仍然是一个空指针之后增加两个节点。那有什么问题?二叉搜索树指针问题

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


typedef struct BinaryNode { 
    int key; 
    double value; 
    struct BinaryNode *left; 
    struct BinaryNode *right; 
    } BinaryNode; 

typedef struct BinaryTree { 
    struct BinaryNode *root; 
    } BinaryTree; 


static void binary_tree_insert_recursive(BinaryNode *current, BinaryNode *new) { 
    if (current == NULL || current->key == new->key) { 
     current = new; 
    } else if (current->key > new->key) { 
     binary_tree_insert_recursive(current->left, new); 
    } else if (current->key < new->key) { 
     binary_tree_insert_recursive(current->right, new); 
    } 
} 

void binary_tree_insert(BinaryTree *tree, int key, double value) { 
    BinaryNode *new = (BinaryNode *) malloc(sizeof(BinaryNode)); 
    new->key = key; 
    new->value = value; 
    binary_tree_insert_recursive(tree->root, new); 
} 

int main(void) { 
    BinaryTree tree; 
    binary_tree_insert(&tree, 5, 123); 
    binary_tree_insert(&tree, 10, 123); 
    printf("%p\n", tree.root); 
    return 0; 
} 

谢谢!

回答

1

我认为current = new;的问题在于您正在更改本地副本current。该功能完成后,此修改不可见。

我怀疑你想要的东西,如:

static void binary_tree_insert_recursive(BinaryNode **current, BinaryNode **new) 
{ 
    if (*current == NULL || (*current)->key == (*new)->key) { 
    *current = *new; 
    /* ... */ 

那么在C FAQ解释。

+0

hm,所以我需要一个双指针。谢谢! – 2011-06-14 19:56:59

+0

@ahojnnes:对于您创建的每个节点,您可能还需要考虑将“左”和“右”指针初始化为NULL。另外,不要将变量命名为“新”,这是令人困惑的。 – Andrei 2011-06-14 20:00:38

+0

@Andrei:默认情况下是不是用空指针初始化的? – 2011-06-14 20:04:57

0

new是关键字。选择一个不同的变量名称。

+2

在C正确的事实并非如此。但是,谁知道OP编译它是什么样的。甚至没有指定编译器或错误消息。 – 2011-06-14 19:51:24

+0

我认为这是C++?尽管如此,它并没有解决问题。 – 2011-06-14 19:52:30

0

current = new所做的就是让变量current指向new指向的东西。没有复制发生,并且该函数对该代码路径没有影响。

1

current是指向节点的指针。当您将它传递到binary_tree_insert_recursivebinary_tree_insert指针的传递。因此,虽然在被调用的函数内部发生了变化,但调用函数并未反映该变化。您需要修改的功能,把你想改变的指针地址

static void binary_tree_insert_recursive(BinaryNode **current, BinaryNode *new) 
{ 
     if (*current == NULL || (*current)->key == new->key) { 
      *current = new; 
+0

也正确答案,谢谢! – 2011-06-14 20:03:57