data-structures · advanced · ~15 min
Implement binary radix trie prefix insertion and longest prefix matching.
Network routers perform Longest Prefix Matching (LPM) on IP routing tables using binary radix tries, branching on each address bit (0 for left, 1 for right).
Given the binary trie node:
typedef struct TrieNode {
struct TrieNode *children[2]; // 0: left, 1: right
int next_hop;
} TrieNode;
Implement prefix insertion and matching:
int trie_insert(TrieNode *nodes, size_t max_nodes, size_t *node_count, uint32_t prefix, uint8_t prefix_len, int next_hop);
int trie_longest_prefix_match(const TrieNode *root, uint32_t ip);
nodes[0]) is the root node. Initialized with children = {NULL, NULL} and next_hop = -1.trie_insert:nodes == NULL, node_count == NULL, prefix_len > 32, or next_hop < 0, return -1.31 down to bit 32 - prefix_len.nodes[*node_count] (if *node_count >= max_nodes, return -1), increment *node_count, initialize child with children = {NULL, NULL} and next_hop = -1.prefix_len bits, set terminal node's next_hop = next_hop.0.trie_longest_prefix_match:root == NULL, return -1.best_hop = root->next_hop.curr->next_hop != -1, update best_hop = curr->next_hop.best_hop (or -1 if no prefix matched).TrieNode arena[64]; size_t count = 1;
arena[0].children[0] = arena[0].children[1] = NULL; arena[0].next_hop = -1;
// 192.168.0.0/16 -> hop 1
trie_insert(arena, 64, &count, 0xC0A80000, 16, 1);
trie_longest_prefix_match(&arena[0], 0xC0A80105); // returns 1
nodes: static node arena; prefix, ip: 32-bit big endian uint32; prefix_len: 0..32.
Returns next hop integer (or -1 if no match).
Zero heap malloc. Static arena allocator.
#include <stddef.h>
#include <stdint.h>
typedef struct TrieNode {
struct TrieNode *children[2];
int next_hop;
} TrieNode;
int trie_insert(TrieNode *nodes, size_t max_nodes, size_t *node_count, uint32_t prefix, uint8_t prefix_len, int next_hop) {
(void)nodes; (void)max_nodes; (void)node_count; (void)prefix; (void)prefix_len; (void)next_hop;
return -1;
}
int trie_longest_prefix_match(const TrieNode *root, uint32_t ip) {
(void)root; (void)ip;
return -1;
}
Checking bits from 0 up instead of 31 down (MSB first); buffer overflow on arena count.
prefix_len == 0 sets default gateway on root; more specific prefix overrides less specific prefix.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.