本题构建二叉树,并且前序遍历输出即可
题目链接hdu3999
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<string>
#include<algorithm>
#include<sstream>
#include<memory>
#include<functional>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a));
#define ll long long int
const int INF = 0x3f3f3f3f;
struct node
{
int val;//根
node *lch,*rch;//左和右
};
int flag;//flag用来标记
node *insert(node *root,int x)//插入
{
if(root==NULL)//如果该点未被填充
{
node *q=new node;//开辟空间
q->val=x;//填充根点
q->lch=q->rch=NULL;//左右子树设为空
return q;//返回建立的根,使得下一次插入的时候知道该点被填充
}
//以下是根点填充后再次开辟空间//
if(x<root->val)//如果x小于根就放入左子树
root->lch=insert(root->lch,x);
else//x大于根反之
root->rch=insert(root->rch,x);
return root;
}
void print(node *root)//前序遍历输出
{
if(root!=NULL)//如果该点未被填充则直接结束
{
//根先输出//
if(flag)//如果该点为第一个输出点,则后面不需要跟空格
printf("%d",root->val);
else//如果不为第一个输出点,后面需要跟空格
printf("% d",root->val);
flag=0;//标记
print(root->lch);//遍历左
print(root->rch);//遍历右
}
}
int main()
{
int n,x;
while(scanf("%d",&n)!=EOF)
{
flag=1;//初始化标记
node *root=NULL;//开辟新顶根,使得第一个插入根一定为空
for(int i=0;i<n;++i)
{
scanf("%d",&x);
root=insert(root,x);//插入
}
print(root);//输出此循环中开辟的树
printf("\n");
}
return 0;
}