PAT A1064

由完全二叉树性质可知,根结点下标为1,任意一个下标为root的结点其左右孩子分别是2*root,2*root+1,(当然下标要小于总结点数)

再由二叉查找树性质可知,中序遍历顺序即结点值的一个有序序列,因此本题由于已知为BST,且已知结点的值,将其排序即可作为中序遍历顺序

#include<bits/stdc++.h>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int tree[1005];
int n;
int id;
int data[1005];
void insert(int root)
{
	if(root>n) return;
	insert(2*root);
	tree[root]=data[++id];
	insert(2*root+1);
}
void windows_cmd_support_utf8(void)
{
	#ifdef WIN32
	    system("chcp 65001 & cls");
	#endif
}
void level_order(int root)
{
	std::queue<int> q;
	q.push(root);
	while(!q.empty())
	{
		int now=q.front();
		q.pop();
		if(now==root) printf("%d",tree[now]);
		else printf(" %d",tree[now]);
		if(2*now<=n) q.push(2*now);
		if(2*now+1<=n) q.push(2*now+1);
	}
}
inline int read()
{
	int w=1,x=0;
	char ch=getchar();
	while(ch>'9'||ch<'0')
	{
		if(ch=='-') w=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-48,ch=getchar();
	return w*x;
}
signed main(void)
{
	windows_cmd_support_utf8();
	n=read();
	for(int i=1;i<=n;i++)
	data[i]=read();
	std::sort(data+1,data+1+n);
	insert(1);
	level_order(1);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值