Trees
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A binary search tree (BST) is made of nodes, each with up to two children. Everything on the left is smaller than the node, and everything on the right is greater or equal:
8
/ \
3 10
/ \ \
1 6 14
struct tree {
int key;
struct tree *left, *right;
};
struct tree *insert(struct tree *t, int key)
{
if (t == NULL) {
struct tree *n = calloc(1, sizeof *n);
n->key = key;
return n;
}
if (key < t->key)
t->left = insert(t->left, key);
else
t->right = insert(t->right, key);
return t;
}
Searching in a balanced tree takes O(log n) — like binary search, but with fast insertions. But if you insert data that's already sorted, the tree degenerates into a list. That's why in practice self-balancing trees are used (red-black, AVL).
In-order traversal: the left subtree → the node → the right subtree. It gives the keys in sorted order:
void inorder(const struct tree *t)
{
if (t == NULL)
return;
inorder(t->left);
printf("%d ", t->key);
inorder(t->right);
}
Task. Insert the numbers from the input into a BST. On the first line, print the keys in in-order traversal; on the second, the height of the tree (an empty tree has height 0, a single node — 1). Free the memory recursively.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.