LinuxN00b LinuxN00b - 19 days ago 5
C Question

Comparing int to NULL in C - is this tutorial incorrect?

I'm looking at this tutorial http://www.learn-c.org/en/Binary_trees and in the insert function it compares an int to NULL. It seems to run fine on the tut site but it didn't work for me and my research tells me it should not work. My code is below.


  1. Am I wrong here or is the tutorial wrong?

  2. If the tutorial is wrong is there any way to dynamically set the value for the first node of the BST? I thought about checking if left and right were both null but that would just keep resetting the first node. Having a third pointer for the value of the node seems wasteful but maybe it's the only way?

    #include <stdio.h>
    #include <malloc.h>
    struct bstNode {
    int val;
    struct bstNode *left;
    struct bstNode *right;
    };

    int insert(struct bstNode *head, int val);

    void printDFS(struct bstNode *head);

    int main() {
    struct bstNode *bstTree = malloc(sizeof(struct bstNode));
    insert(bstTree, 8);
    insert(bstTree, 5);
    insert(bstTree, 98);
    insert(bstTree, 2);
    insert(bstTree, 15);
    insert(bstTree, 65);
    insert(bstTree, 15);
    printDFS(bstTree);
    }

    int insert(struct bstNode *head, int val) {
    //This is the problem statement, it contains random data when I debug as it's uninitialized
    if (head->val == NULL) {
    head->val = val;
    return 0;
    }

    if (val < head->val) {
    if (head->left != NULL) {
    return insert(head->left, val);
    } else {
    head->left = malloc(sizeof(struct bstNode));
    head->left->val = val;
    return 0;
    }
    } else {
    if (head->right != NULL) {
    return insert(head->right, val);
    } else {
    head->right = malloc(sizeof(struct bstNode));
    head->right->val = val;
    return 0;
    }
    }
    }

    void printDFS(struct bstNode *head) {
    if (head->left != NULL) printDFS(head->left);
    printf("%d ", head->val);
    if (head->right != NULL) printDFS(head->right);
    }


Answer

Comparing the value in your tree to NULL is bad. Here is a correct implementation of a binary search tree:

http://cslibrary.stanford.edu/110/BinaryTrees.html