Insertion Order
Time limit2sMemory limit512 MB
Find a permutation of 1 to n whose insertion order into an unbalanced BST yields a tree of height exactly k, or report impossible.
- Level
Medium7 of 10
- Topics
- Tree, Greedy, Recursion, Implementation
- Solved
- No attempts yet
Problem
A friend of yours is taking a class on algorithms and data structures. Last week he learned about binary search trees, and along with them the importance of using self-balancing trees to keep the tree height low and guarantee fast access to every node.
A binary search tree is a binary tree in which each node stores a key, with the property that the key of each node is greater than all keys in the left subtree of that node and less than all keys in the right subtree. A new key is inserted by adding a new leaf node with that key at the only position where the property is preserved, as shown in the figure below.

Figure I.1: The first sample case.
To show him how bad things can get without self-balancing, you want to demonstrate that trees of almost any height can be built by carefully choosing the insertion order.
You are given two integers n and k and want to construct a binary search tree with n nodes and height k. The height of a tree is the maximal number of nodes on a path from the root to a leaf. To do this, you need to find a permutation of the integers from 1 to n such that inserting them into an empty binary search tree in that order (without self-balancing) produces a tree of height k.
Input
The input consists of two integers n and k (1 ≤ k ≤ n ≤ 2 · 105). Here n is the number of nodes in the tree and k is the exact height the tree should have.
Output
If there is no solution, output impossible. Otherwise, output one line with n integers, the requested permutation. If there is more than one solution, any one of them will be accepted.