hdu3999 The order of a Tree

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3999

题意:给一序列,按该序列插入二叉树,给出字典序最小的插入方法建相同的一棵树出来。即求二叉树的先序遍历。

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int v;
    node *left,*right;
}*root;
node* build(node *root,int v)
{
    if(root==NULL)
    {
        root=new node();
        root->v=v;
        root->left=root->right=NULL;
    }
    else if(v<=root->v)root->left=build(root->left,v);
    else root->right=build(root->right,v);
    return root;
}

int flag;
void dfs(node *root)
{
    if(flag==1)cout<<root->v,flag=0;
    else cout<<" "<<root->v;
    if(root->left!=NULL)dfs(root->left);
    if(root->right!=NULL)dfs(root->right); 
}
int main()
{
    int n;
    while(cin>>n)
    {
        flag=1;
        root=NULL;
        int tmp;
        for(int i=0;i<n;i++)cin>>tmp,root=build(root,tmp);
        dfs(root);
        cout<<endl;
    } 
    return 0;
} 
posted @ 2019-12-12 14:08  myrtle  阅读(227)  评论(0编辑  收藏  举报