Got MLE in C using Trie


  • 0
    S

    Here is my code, I released the memory but seems no help.

    struct TrieNode {
        struct TrieNode* children[2];
    };
    
    struct TrieNode* createNode() {
        struct TrieNode* node = (struct TrieNode *)malloc(sizeof(struct TrieNode));
        node->children[0] = NULL;
        node->children[1] = NULL;
        return node;
    }
    
    void insert(struct TrieNode* root, int val) {
        int i, bit;
        struct TrieNode* node = root;
        for (i = 31; i >= 0; i--) {
            bit = (val >> i) & 1;
            if (node->children[bit] == NULL) {
                node->children[bit] = createNode();
            }
            node = node->children[bit];
        }
    }
    
    int findMax(struct TrieNode* root, int val) {
        int i, bit, sum = 0;
        struct TrieNode* node = root;
        for (i = 31; i >= 0; i--) {
            bit = (val >> i) & 1;
            if (node->children[bit ^ 1] != NULL) {
                sum += (1 << i);
                node = node->children[bit ^ 1];
            } else {
                node = node->children[bit];
            }
        }
        return sum;
    }
    
    int freeNode(struct TrieNode* root) {
        if (root == NULL) {
            return;
        }
        freeNode(root->children[0]);
        freeNode(root->children[1]);
        free(root);
    }
    
    int findMaximumXOR(int* nums, int numsSize) {
        struct TrieNode *root = createNode();
        int i, max = 0, temp;
        for (i = 0; i < numsSize; i++) {
            insert(root, nums[i]);
        }
        
        for (i = 0; i < numsSize; i++) {
            temp = findMax(root, nums[i]);
            max = max > temp ? max : temp;
        }
        freeNode(root);
        return max;
    }
    

  • 1

    @shilaimuslm It's accepted now.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.