码迷,mamicode.com
首页 > 其他好文 > 详细

hdu3999 The order of a Tree

时间:2019-12-12 14:49:32      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:方法   style   acm   name   clu   oid   pid   tree   else   

题目链接: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;
} 

 

 

 

hdu3999 The order of a Tree

标签:方法   style   acm   name   clu   oid   pid   tree   else   

原文地址:https://www.cnblogs.com/myrtle/p/12028819.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!