二叉搜索树获得0而不是null

时间:2014-03-31 15:35:14

标签: c binary-search-tree

我一直在尝试清除我的二叉树,当这样做时,我从下面的代码中得到0而不是null。当树引用NULL但未发生时,该树被定义为空。在遍历树时可以看到错误。如何更改它,以便在插入第二组数字时,0不会显示?

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

    typedef struct Node{
            int value;
            struct Node * left;
            struct Node * right;

    } Node;

    Node * insert(Node * node, int value){
        if(node == NULL){
            Node *temp;
            temp = (Node *)malloc(sizeof(Node));
            temp->value = value;
            temp->left = temp->right = NULL;
            return temp;
        }
        if(value >(node->value)){
            node->right = insert(node->right,value);
        }
        else if(value < (node->value)){
            node->left = insert(node->left,value);
        }
        return node;
    }

    void inorder(Node * node){
        if(node == NULL) {
            return;
        }
        inorder(node->left);
        printf("%d ", node->value);
        inorder(node->right);
    }

    void preorder(Node * node){
            if(node == NULL){
                return;
            }
            printf("%d ",node->value);
            preorder(node->left);
            preorder(node->right);
    }

    void postorder(Node *node){
            if(node == NULL){
                return;
            }
            postorder(node->left);
            postorder(node->right);
            printf("%d ",node->value);
    }

   /* issue here is produces a 0 instead of null and that can be seen in the traversing :( */
    void empty(Node * node) {
        if (node->left)
            node->left = NULL;
        if (node->right)
            node->right = NULL;
        if (node->value)
            node->value = NULL;
        node->value = NULL;
    }

    int main(){

            Node * root = NULL;
            root = insert(root, 5);
            root = insert(root, -1);
            root = insert(root, 3);
            root = insert(root, -14);
            root = insert(root, 8);
            root = insert(root, 10);
            root = insert(root, 9);
            root = insert(root, 6);

            inorder(root);
            printf("\n");
            preorder(root);
            printf("\n");
            postorder(root);
            printf("\n");

            empty(root);

            root = insert(root, 1);
            root = insert(root, 2);       
            root = insert(root, 3); 

            inorder(root);
            printf("\n");
            preorder(root);
            printf("\n");
            postorder(root);
            printf("\n");      

    }

2 个答案:

答案 0 :(得分:1)

void empty(Node ** node) {
    if(*node){
        empty(&(*node)->left);
        empty(&(*node)->right);
        free(*node);
        *node = NULL;
    }
}
...
//at main
empty(&root);

答案 1 :(得分:0)

您为value分配NULL,但valueint,因此NULL ptr将转换为int类型 - 此类转换的结果为零。

顺便说一句,为指针变量赋值NULL会替换指针的值,但不会释放指针所指向的内存块。