data-structures · intermediate · ~15 min
Recursive tree traversal that produces output.
Flatten a binary search tree into a sorted array via an in-order traversal (left, self, right).
The grader supplies the same node type as the previous exercise:
typedef struct bst { int v; struct bst *l, *r; } bst_t;
Implement void bst_inorder(const bst_t *root, int *out, size_t *idx) that writes the tree's values in ascending order into out, starting at index *idx and advancing *idx by one per node. No main — the grader calls it.
root: the tree root, or NULL.out: a caller-provided array large enough to hold all values.idx: pointer to the current write position; updated as you append.Nothing is returned. After the call, out[old *idx .. ] holds the in-order (sorted) values and *idx has advanced by the number of nodes visited.
BST {5,3,8,1,4,9} -> out = {1,3,4,5,8,9}, *idx increased by 6
root == NULL: write nothing and leave *idx unchanged.idx by pointer so calls accumulate.root (or NULL), an out array, and a pointer idx to the current write position.
Nothing returned; out gets the sorted values and *idx advances by the node count.
out must be large enough; NULL tree leaves *idx unchanged.
#include <stddef.h>
void bst_inorder(const bst_t *root, int *out, size_t *idx) {
/* TODO */
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.