• A1064. Complete Binary Search Tree (30)


    A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

    • The left subtree of a node contains only nodes with keys less than the node's key.
    • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
    • Both the left and right subtrees must also be binary search trees.

    A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.

    Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

    Input Specification:

    Each input file contains one test case. For each case, the first line contains a positive integer N (<=1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.

    Output Specification:

    For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

    Sample Input:

    10
    1 2 3 4 5 6 7 8 9 0
    

    Sample Output:

    6 3 8 1 5 7 9 0 2 4
     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <iostream>
     4 #include <string.h>
     5 #include <math.h>
     6 #include <algorithm>
     7 #include <string>
     8 #include <stack> 
     9 #include <queue>
    10 using namespace std;
    11 const int maxn=1010; 
    12 int n,number[maxn],CBT[maxn];
    13 int shuzucount=0;
    14 
    15 void inOrder(int root)//这里中序遍历的目的是,
    16 {//将中序的结果数组num与过程结合,得到CBT 
    17    if(root>n)return;
    18    inOrder(root*2);
    19    CBT[root]=number[shuzucount++];
    20    inOrder(root*2+1);    
    21 }
    22 int main(){
    23    scanf("%d",&n);
    24    for(int i=0;i<n;i++)
    25    {
    26        scanf("%d",&number[i]);
    27    }
    28    sort(number,number+n);
    29    inOrder(1);
    30       for(int i=1;i<=n;i++)
    31       {
    32           printf("%d",CBT[i]);
    33           if(i<n)printf(" ");
    34        } 
    35     return 0;
    36 }
  • 相关阅读:
    Hashset 常用的方法
    List新增的方法
    关于集合
    转载关于sql 注入
    可变参数和preparestatement 结合使用
    数据库连接 中的测试事例,包括工具类,配置文件,查询,增加,以及查询后返回对象
    在静态方法中不能调用非静态变量,但getclass()可以换个形式来调用
    用一个对象中读出信息进行出入的代码片段
    新建maven项目更改 web版本
    elasticsearch 局部更新
  • 原文地址:https://www.cnblogs.com/ligen/p/4322579.html
Copyright © 2020-2023  润新知