data-structures · intermediate · ~15 min

BST inorder to array

Recursive tree traversal that produces output.

Challenge

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;

Task

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.

Input

  • 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.

Output

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.

Example

BST {5,3,8,1,4,9}   ->   out = {1,3,4,5,8,9}, *idx increased by 6

Edge cases

  • root == NULL: write nothing and leave *idx unchanged.

Rules

  • Recurse left, append the node, recurse right; pass idx by pointer so calls accumulate.

Input format

root (or NULL), an out array, and a pointer idx to the current write position.

Output format

Nothing returned; out gets the sorted values and *idx advances by the node count.

Constraints

out must be large enough; NULL tree leaves *idx unchanged.

Starter code

#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.