PAT 1064. 完全二叉搜索树
原题链接
中等
作者:
YAX_AC
,
2024-11-28 17:50:28
,
所有人可见
,
阅读 7
// Complete Binary Search Tree(CBT)完全二叉搜索树
//A Binary Search Tree (BST)二叉搜索树
//binary 二元的,二进制的 subtree子树 traversal遍历
//possible exception可能的例外 bottom level底层
//A Complete Binary Tree (CBT) is a tree that is completely filled,
//with the possible exception of the bottom level,
//which is filled from left to right.
//完整二叉树(CBT)是一种完全填充的树,但底层可能除外,底层是从左向右填充的。
//You are supposed to output the level order traversal sequence of this BST.
//您应该输出此BST的级别顺序遍历序列。
//keys权值
//print in one line the level order traversal sequence of the corresponding complete binary search tree
//输出给定完全二叉搜索树的层序遍历序列。
//1.n个结点构造成完全二叉树
//2.按中序遍历的顺序将n个权值填进去,使其满足二叉搜索树(BST)的性质
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1010;
int n;
int w[N];//权值
int tr[N];//树
void dfs(int u,int& k)//中序遍历
{
if(u*2 <= n) dfs(u*2,k);//左子树
tr[u] = w[k++];
if(u*2+1<=n) dfs(u*2+1,k);//右子树
}
int main()
{
cin>>n;
for(int i = 0; i<n; i++) cin>>w[i];
sort(w,w+n);
int k = 0;
dfs(1,k);
cout<<tr[1];
for(int i = 2; i<=n; i++) cout<<' '<<tr[i];
cout<<endl;
return 0;
}