aboutsummaryrefslogtreecommitdiff
path: root/comp2521/tf_idf/invertedIndexTree.c
blob: b66d6a8d1acb7ab8f83e539a3c7088a1e983af2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include "invertedIndexTree.h"

// Returns a newly malloc'ed inverted index node, fields initialised to zero
// except for word.
struct InvertedIndexNode *createInvertedIndexNode(char *const word) {
    struct InvertedIndexNode *ret = calloc(1, sizeof(struct InvertedIndexNode));
    ret->word = word;
    return ret;
}

// Inserts to a FileListNode BST. Uses strcmp to determine priority, with
// negative values moving into the left and positive values into the right.
struct InvertedIndexNode *
insertInvertedIndexNode(struct InvertedIndexNode *node, char *const word) {
    if (node == NULL) {
        return createInvertedIndexNode(word);
    }

    const int comparison = strcmp(word, node->word);
    if (comparison < 0) {
        node->left = insertInvertedIndexNode(node->left, word);
    }
    if (comparison > 0) {
        node->right = insertInvertedIndexNode(node->right, word);
    }
    return node;
}

// Searches for an invertedIndexNode via a string.
struct InvertedIndexNode *
searchInvertedIndexNode(struct InvertedIndexNode *head, char *const word) {
    int comparison = strcmp(word, head->word);
    if (head == NULL || !comparison) {
        return head;
    }
    if (comparison < 0) {
        return searchInvertedIndexNode(head->left, word);
    }
    return searchInvertedIndexNode(head->right, word);
}