二叉搜索树的中序遍历为有序序列,利用此序列中序构建完全二叉树即完全二叉搜索树
一个无重复的非负整数序列,必定对应唯一的一棵形状为完全二叉树的二叉搜索树。本题就要求你输出这棵树的层序遍历序列。
输入格式:
首先第一行给出一个正整数 N(≤1000),随后第二行给出 N 个不重复的非负整数。数字间以空格分隔,所有数字不超过 2000。
输出格式:
在一行中输出这棵树的层序遍历序列。数字间以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
10
1 2 3 4 5 6 7 8 9 0
输出样例:
6 3 8 1 5 7 9 0 2 4
//线索树的中序遍历是递增序列(左子树值小于右子树)。
//将递增的序列按照中序递归建树即为二叉搜索树。
#include <bits/stdc++.h>
using namespace std;
typedef int elemType;
typedef struct BiTNode
{
elemType data;
BiTNode *Lchild,*Rchild;
}BiTNode,*BiTree;
int n,LDR[1001],k=1;
BiTree creatBiTree(int i)
{
if(i>n) return NULL;
BiTree T=(BiTree)malloc(sizeof(BiTNode));
T->Lchild=creatBiTree(i*2);//此后三行体现中序递归建树。
T->data=LDR[k++];
T->Rchild=creatBiTree(i*2+1);
return T;
}
void LevelVist(BiTree T)//树的层序遍历。
{
int i=0;
queue<BiTree> Q;
Q.push(T);
while(!Q.empty())
{
if(!i++) cout<<Q.front()->data;
else cout<<" "<<Q.front()->data;
if(Q.front()->Lchild) Q.push(Q.front()->Lchild);//入队为空导致程序段错误。
if(Q.front()->Rchild) Q.push(Q.front()->Rchild);
Q.pop();
}
cout<<endl;
}
int main()
{
BiTree T=(BiTree)malloc(sizeof(BiTNode));
cin>>n;
for(int i=1;i<=n;i++)
cin>>LDR[i];
sort(LDR+1,LDR+n+1);
T=creatBiTree(1);
LevelVist(T);
}