Binary Search Tree Code
InterviewTime limit1sMemory limit128 MB
Given n and k, output the n-th preorder string among all BSTs built from the first k letters, listed in alphabetical order.
- Level
Medium7 of 10
- Topics
- Tree, Recursion, Combinatorics, Binary search
- Solved
- No attempts yet
Problem
A binary tree is either empty, or it consists of one vertex together with two trees linked to it. These two trees are called the left subtree and the right subtree. Each vertex holds one lowercase letter of the English alphabet. The vertex that is not a subtree of any other vertex is called the root.
A tree is a binary search tree (BST) if the following condition holds at every vertex: all letters in the left subtree precede, in alphabetical order, the letter at the root, and all letters in the right subtree follow the letter at the root.
The code of a BST is defined as follows.
- If the tree is empty, the code is the empty string (0 letters).
- Otherwise, it is the letter at the root, followed by the code of the left subtree, followed by the code of the right subtree.
Consider every BST that has vertices holding the first letters of the English alphabet. Write the codes of all such trees in alphabetical order. The -th code in that list is called the -code.
For example, there are exactly 14 BSTs with 4 vertices, and their codes in alphabetical order are:
abcd abdc acbd adbc adcb bacd badc cabd cbad dabc dacb dbac dcab dcba
The string badc is the -code, and it corresponds to the BST shown below.

Write a program that:
- reads the two integers and from standard input,
- finds the -code, and
- writes it to standard output.
Input
The first and only line of standard input contains two positive integers and , separated by a single space, with . The value is not greater than the total number of codes of BSTs with vertices.
Output
The first and only line of standard output must contain exactly one word, written in lowercase letters, which is the -code.