1064 Complete Binary Search Tree (30分)

题意:
给你一串完全二叉搜索树的值,要求你输出该完全二叉搜索树的层序遍历。

分析:
由于是完全二叉搜索树,完全二叉搜索树的中序遍历,即为这组数值从小到大排序。之后递归得到层序遍历。

代码:

#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
vector<int>arr;
vector<int>res(1005);
int Getleftlength(int n){
	int i=1;
	while(1){
		if(n<=pow(2,i)-1)
		break;
		i++;//求该数的层数
	}
	if(n-pow(2,i-1)>=pow(2,i-2))//判断最后一层的结点是否在右子树
	return pow(2,i-1)-1;
	else
	return n-pow(2,i-2);
}
void solve(int left,int right,int root){
	int n=right-left+1;
	if(n==0)
	return;
	int l=Getleftlength(n);//求左子树规模
	res[root]=arr[left+l];
	int leftchild=2*root+1;
	int rightchild=leftchild+1;
	solve(left,left+l-1,leftchild);
	solve(left+l+1,right,rightchild);
}
int main(){
	int n;
	scanf("%d",&n);
	for(int i=0,t;i<n;++i){
		scanf("%d",&t);
		arr.push_back(t);
	}
	sort(arr.begin(),arr.end());
	solve(0,n-1,0);
	for(int i=0;i<n;++i){
		if(i)
		cout<<" ";
		cout<<res[i];
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

博&人&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值