data-structures · intermediate · ~15 min

BST insert

Recursive insertion in a binary search tree.

Challenge

Given

typedef struct bst { int v; struct bst *l, *r; } bst_t;

implement bst_t *bst_insert(bst_t *root, int v) returning the (possibly new) root after inserting v. Duplicates are ignored — if v already exists, return the root unchanged.

Starter code

#include <stdlib.h>

bst_t *bst_insert(bst_t *root, int v) {
    /* TODO */
    return root;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.