PAT甲级1064 Complete Binary Search Tree (30分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

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

二、解题思路

完全二叉搜索树的中序遍历转层序遍历,如果按照平常的建立二叉搜索树的做法就很复杂了,而且也没有有效利用题目的条件。二叉搜索树的中序遍历一定是按元素从小到大排的,那么第一个元素一定是在二叉树的左下角,第二个元素则是它的父亲节点,第三个元素则是父亲节点的第二个孩子,这不就很像我们的中序遍历吗,所以可以利用这个思想设计一个递归程序解出此题。

三、AC代码

#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;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108659878