The order of a Tree(二叉树的前序遍历)(hdu3999)

本题构建二叉树,并且前序遍历输出即可
题目链接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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值