PTA甲级考试真题练习64——1064 Complete Binary Search Tree

题目

在这里插入图片描述

思路

首先是完全二叉树,所以用线性数组存储,然后发现中序遍历完全二叉搜索树得到的是一个递增序列,所以我们可以将给定数据排序后,按照中序遍历构造完全二叉搜索树,然后在层序输出即可

代码

#include <iostream>
#include <string>
#include<algorithm>
#include<vector>
#include<queue>

using namespace std;
#define nmax 1010
#define inf 999999
int BST[nmax];
vector<int> seq;
int _size;
int k = 0;

void DFS(int i)
{
	if(2*i<=_size)
		DFS(2 * i);
	BST[i] = seq[k];
	++k;
	if(2*i+1<=_size)
		DFS(2 * i + 1);
}

void LevelPrint()
{
	queue<int> q;
	cout << BST[1];
	if (2 * 1 <= _size)
		q.push(2);
	if (2 * 1 + 1 <= _size)
		q.push(3);
	while (!q.empty()) {
		int i = q.front();
		cout << " " << BST[i];
		q.pop();
		if (2 * i <= _size)
			q.push(2*i);
		if (2 * i + 1 <= _size)
			q.push(2*i+1);
	}
}
int main()
{
	int n;
	cin >> n;
	_size = n;
	seq.resize(n);
	for (int i = 0; i < n; ++i)
		cin >> seq[i];
	sort(seq.begin(), seq.end());
	DFS(1);
	LevelPrint();
	return 0;
}
发布了153 篇原创文章 · 获赞 4 · 访问量 3799

猜你喜欢

转载自blog.csdn.net/qq_43647628/article/details/105253114