data-structures · intermediate · ~15 min
Recursive insertion in a binary search tree.
Insert a value into a binary search tree, keeping the BST ordering and ignoring duplicates.
The grader supplies this node type:
typedef struct bst { int v; struct bst *l, *r; } bst_t;
Implement bst_t *bst_insert(bst_t *root, int v) that inserts v and returns the (possibly new) root. No main — the grader calls it.
root: the current root, or NULL for an empty tree.v: the value to insert.The root of the tree after insertion. Smaller values go left, larger go right. If v already exists, the tree is unchanged and the same root is returned.
insert 5,3,8,1,4 then an in-order walk -> 1,3,4,5,8
inserting a duplicate (e.g. another 3) -> no new node added
malloc; reassign child links from the recursive call so new subtrees attach.root (or NULL) and the int value v to insert.
The root after inserting v (unchanged if v already exists).
Allocate nodes with malloc; duplicates are ignored.
#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.