PAT A급 1064 Complete Binary Search Tree(30점) 완전 두 갈래 나무, BST

1064 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

    해석: 입력 데이터에 대한 정렬을 먼저 합니다. BST의 중차 역행 결과는 점차적으로 증가하고, BST의 중차 역행 결과는 점차적으로 증가하기 때문입니다. (중요한 일은 세 번!!!)그래서 중서 역행 결과를 얻을 수 있어요.
    그래서 DFS 모방을 통해 대응하는 위치의 데이터를 반복해서 구하는 것이 틀림없다. i위치의 왼쪽 결점은 2i, 오른쪽 결점은 2i+1에 대응한다
    마지막으로 BSF를 통해 반복 결과를 구합니다
    #include
    #include
    #include
    using namespace std;
    
    const int maxn = 1e3 + 10;
    int a[maxn],b[maxn],index = 0; 
    int n;
    
    //  
    void dfs(int x){
    	if(x > n)return;
    	dfs(x << 1);//2x
    	b[x] = a[index++];
    	dfs((x << 1) | 1);//2x+1 
    }
    
    int main(){
    
    	scanf("%d",&n);
    	for(int i = 0;i

    좋은 웹페이지 즐겨찾기