Easy BST

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Wastematerial/article/details/45427165
Description

BST (Binary Search Tree) is an efficient data structure for searching. In a BST all the elements of the left sub-tree are smaller and those of right sub-tree are greater than the root.                          

Normally, we construct BST by successively inserting an element. In that case, the ordering of elements has great impact on the structure of the tree. Look at the following cases:

In this problem, you have to find the order of 1 to N integers such that the BST constructed by them has height of at most H. The height of a BST is defined by the following relation –

  1. BST having no node has height 0.

  2. Otherwise, it is equal to the maximum of the height of the left sub-tree and right sub-tree plus 1.

Again, several orderings can satisfy the criterion. In that case we prefer the sequence where smaller numbers come first. For example, for N=4, H=3 we want the sequence 1 3 2 4 rather than 2 1 4 3 or 3 2 1 4.

Input

Each test case starts with two positive integers N (1 ≤ N ≤ 10000) and H (1 ≤ H ≤ 30). Input is terminated by N=0, H=0. This case should not be processed. There can be at most 30 test cases.

Output

Output of each test case should consist of a line starting with "Case #: ", where '#' is the test case number. It should be followed by the sequence of N integers in the same line. There must not be any trailing space at the end of the line. If it is not possible to construct such tree then print "Impossible." (without the quotes).

Sample Input

4 3
4 1
6 3
0 0

Sample Output

Case 1: 1 3 2 4
Case 2: Impossible.
Case 3: 3 1 2 5 4 6

这是一道比较水的题;

这道题涉及到了二叉搜索树,不过又比较简单一点。

结构特点:

二叉搜索树的特点是,小的值在左边,大的值在右边,即

比如:

这样的结构有一个好处是很容易获得最大值(Maximum)、最小值(minimum)、某元素的前驱(Precursor)、某元素的后继(Successor)。

最大值:树的最右节点。

最小值:树的最左节点。

某元素前驱:左子树的最右。

某元素的后继:右子树的最左。

上面可以发现每棵子树如果有左子树,那么该结点的值=子树的结点数量+1;

在上面那题中树的高度等于左右子树的高度最大值+1;

我们可以发现左子树的值=结点的值-2^(t-1),(设子叶高度为1,t为结点的高度),右子树的值=结点的值+2^(t-1);

          4

      2        6

   1     3   7    8

可以看出2=4-2^1.

我们可以把整棵树看成一个结点的左子树,用深搜来遍历;

#include <stdio.h>
#include <math.h>
void dfs(int x,int y,int z)//x:结点值,y:高度,z为左右子树,设左为0,右为1;
{
    if(y==0)
        return ;
    int t;//子树的值
    if(z==0)
       t=x-pow(2,y-1);
    else
        t=x+pow(2,y-1);
    if(t>0)
    {
        printf(" %d",t);
        dfs(t,y-1,0);//左子树
        dfs(t,y-1,1);//右子树
    }
    return ;
}
int main()
{
    int n,h,i;
    i=1;
    while(scanf("%d%d",&n,&h)&&(n+h))
    {
        printf("Case %d:",i);
        if(n>pow(2,h)-1)//如果数字大于高度满树的情况则不可能成树
            printf(" Impossible.\n");
        else
        {
            dfs(n+1,h,0);//把整棵树看成一个结点的左子树,那么这个结点为n+1
            printf("\n");
        }
        i++;
    }
    return 0;
}
新手博客,望大神指教 微笑


猜你喜欢

转载自blog.csdn.net/Wastematerial/article/details/45427165
BST
今日推荐