开发者

binary search tree pointer problem

I tried to implement a binary search tree for the purpose of (re-)learning C. The problem is that the this current = new; does not work as desired because the tree.root is still a null pointer after adding two nodes. What's wrong with that?

#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->开发者_C百科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;
}

Thank you!


I believe the problem with current = new; is that you are changing your local copy of current. After the function is done, this modification is not visible.

I suspect you want something like:

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

Well explained in the C FAQ.


current is a pointer to a node. When you pass it to binary_tree_insert_recursive from binary_tree_insert the value of the pointer is passed. So although it is changed inside the called function, the change is not reflected in the calling function. You need to modify the function to take the address of the pointer you wish to change:

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


all that current = new does is make it so that the variable current points at the thing that new is pointing at. No copying takes place, and the function has no effect on that codepath.


new is a keyword. Choose a different variable name.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜