PAT Grade A 1064 Complete Binary Search Tree (30 points)|C++ implementation

1. Title description

Original title link
Insert picture description here

Input Specification:

Insert picture description here

​​Output Specification:

Insert picture description here

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

Two, problem-solving ideas

From the middle-order traversal of the complete binary search tree to the layer-order traversal, it is very complicated to build a binary search tree according to the usual practice, and there is no condition to effectively use the problem. The middle order traversal of the binary search tree must be sorted by elements from small to large, then the first element must be in the lower left corner of the binary tree, the second element is its parent node, and the third element is the parent node The second child of, isn’t this very similar to our in-order traversal, so we can use this idea to design a recursive program to solve this problem.

Three, AC code

#include<iostream>
#include<algorithm>
using namespace std;
int in[1010], level[1010], n, t = 0;
void inOrder(int root)
{
    
    
    if(root >= n)   return;
    inOrder(root*2 + 1);
    level[root] = in[t++];
    inOrder(root*2 + 2);
}
int main()
{
    
    
    scanf("%d", &n);
    for(int i=0; i<n; i++)  scanf("%d", &in[i]);
    sort(in, in+n);
    inOrder(0);
    printf("%d", level[0]);
    for(int i=1; i<n; i++)  printf(" %d", level[i]);
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_42393947/article/details/108659878