A1064 Complete Binary Search Tree [下标建树/bst]

在这里插入图片描述
因为每个结点左子节点下标2i 右2i+1 然后开一个数组,因为是完全二叉搜索树,可以用数组来存值,讲赋值的数组从小到大排序然后直接中序遍历赋值,因为中序遍历是左根右,从小到大的顺序。

#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn = 1010;
int cbt[maxn],number[maxn],n;
int index = 0;
void inorder(int root)
{
	if (root > n) return;
	inorder(root * 2);
	cbt[root] = number[index++];
	inorder(root * 2 + 1);
}
int main()
{
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> number[i];
	}
	sort(number, number + n);
	inorder(1);
	for (int i = 1; i <= n; i++)
	{
		cout << cbt[i];
		if (i + 1 <= n)
			cout << " ";
	}
}
原文地址:https://www.cnblogs.com/Hsiung123/p/13812007.html