A1064 Complete Binary Search Tree (30 分| 二叉查找树,附详细注释,逻辑分析)
其他
2020-03-28 11:24:58
阅读次数: 0
写在前面
- 思路分析
- 给你1个序列,所有的数都非负且不同,用这个序列建一个完全二叉搜索树,再给出这个树的层序序列
- 解题思路:
- 二叉搜索树的中序序列是有序的,那么我们把输入的序列进行排序,得到这棵BST的中序序列
- 再按中序遍历的方式建树,得到这棵完全二叉搜索树
- 因为是完全二叉树,所以可以用一个数组来保存,且有n个结点,一定会把前面n个空间占满。
- 输出层序序列
- 热点知识,参考代码易理解
测试用例
ac代码
-
#include<iostream>
#include<cstdio>
#include<string>
#include<queue>
#include<stack>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=1010;
int num[maxn],cbt[maxn],n,inx=0;
void inorder(int root)
{
if(root>n)
return;
inorder(2*root);
cbt[root]=num[inx++];
inorder(2*root+1);
}
int main()
{
cin>>n;
for(int i=0; i<n; i++)
cin>>num[i];
sort(num,num+n);
inorder(1);
for(int i=1; i<=n; i++)
{
cout<<cbt[i];
if(i<n)
cout<<" ";
}
return 0;
}
发布了328 篇原创文章 ·
获赞 107 ·
访问量 39万+
转载自blog.csdn.net/qq_24452475/article/details/100621095