编程介的小学生 2017-03-24 03:34 采纳率: 20.3%
浏览 902
已采纳

The Kth BST

Definition: A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree.

Definition: A binary search tree(BST) is a binary tree. It may be empty. If it is not empty, it satisfies the following properties:

Every elements has a key, and no two elements have the same key, that is, the keys are unique.
The keys in a nonempty left subtree must be smaller than the key in the root of the subtree.
The keys in a nonempty right subtree must be larger than the key in the root of the subtree.
The left and right subtrees are also binary search trees.
In this problem, we just care about the Preorder Traversal of a BST. Here is the pseudocode for Preorder Traversal:

void preorder(tree_pointer ptr)
/* preorder tree traversal */
{
if (ptr) {
printf("%d", ptr->data);
preorder(ptr->left_child);
preorder(ptr->right_child);
}
}
Now, you are given n, the number of nodes in a BST, and the nodes of the BST are consist of the first n lowcase letters. Of course, more than one BST can be constructed except when n is 1. You task is to sort there BST's according to their preorder representations, and gives out the Kth BST.

For example, when n is 2, there are two BST's can be constructed, as following:

a b
\ /
b a
Their preorder representations are: ab and ba, so the first one is ab, and the second one is ba.

Input

There are multiple test cases in this problem. The input is terminated by EOF.

For each test case, there are two inputs: n and K, representing the number of nodes in the BST, and the index of the BST you need to output.

Note:

n is between 1 and 19
K is between 1 and the number of ways to construct the BST
Output

For each input, you should first output the Kth preorder representation of the BST. Next, for each node (in the order a, b, c, ...), output it first, then output the left sub node (output * if not exist) and the right sub node (output * if not exist), seperated by a single blank space. K will not be greater than the number of representations of BST given n nodes. Output a blank line between two test cases.

Sample Input

2 2
4 9
Sample Output

ba
a * *
b a *

cbad
a * *
b a *
c b d
d * *

  • 写回答

2条回答 默认 最新

  • threenewbee 2017-04-01 15:11
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路