PAT甲级真题 1064 完全二叉搜索树

题面

在这里插入图片描述

题解

  1. 对于二叉搜索树,它的中序遍历是有序的(从小到大),先排序再模拟中序遍历将逐个结果填进去即可的得到层序遍历结果
  1. 完全二叉排序树可以只用一个一维数组来存储,下标从 1开始左孩子为 2n 右孩子为 2n+1 (若存在)

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 1100;

int n;
int tree[N];
int inorder[N];
int idx = 0;

void dfs(int root) {
    
    
    if (root > n) return;
    dfs(root * 2);
    inorder[root] = tree[idx++];
    dfs(root * 2 + 1);
}

int main() {
    
    

    cin >> n;
    for (int i = 0; i < n; i++) cin >> tree[i];
    sort(tree, tree + n);
    dfs(1);

    for (int i = 1; i <= n; i++) {
    
    
        if (i == n) cout << inorder[i] << endl;
        else cout << inorder[i] << " ";
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/115128118