题目描述:
A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than or equal to the node's key. Both the left and right subtrees must also be binary search trees. 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. Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.
翻译:一个二叉搜索树递归地表示为带有以下特点的二叉树
①左子树的节点的值都小于当前节点的值
②右子树的节点的值都大于等于当前节点的值
左子树和右子树也同时符合二叉搜索树的特点
一个完全二叉树是完全填充的树,除了最底层,是从左到右填充
现在给定一系列不同的非负整数值,如果需要树也必须是CBT,则可以构造唯一的BST。您应该输出这个BST的层序遍历序列。
过程:
①先构造一个二叉树,利用完全二叉树的性质
void creatTree(int root)
{
if(root>N) return ;
int lchild = root * 2, rchild = root *2 + 1;
creatTree(lchild);
tree[root] = node[pos++]; //利用数组存储树的节点
creatTree(rchild);
}
将输入的测试的数据进行排序,从小到大,再依次中序放入数组,最后对数组进行输出,即可得到所要的输出。
完整代码段
#include <iostream>
#include<algorithm>
using namespace std;
int tree[1010];
int node[1010];
int pos = 1;
void creatTree(int root, int N)
{
if (root > N) return ;
int lchild = root * 2;
int rchild = root * 2 + 1;
creatTree(lchild,N);
tree[root] = node[pos++];
creatTree(rchild,N);
}
bool cmp(int a, int b){
return a<b;
}
int main()
{
int N;
cin>>N;
for(int i=1;i<=N;i++)
cin>>node[i];
sort(node+1,node+N+1,cmp);
creatTree(1,N);
cout<<tree[1];
for(int j = 2;j <= N;j++)
cout<<" " <<tree[j];
}