hdu 3999 The order of a Tree

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

typedef struct node *tree;
typedef struct node
{
    tree left;
    tree right;
    int data;
};
bool f;
tree in(int t,tree p)
{
    if(!p)
    {
        p=(tree)malloc(sizeof(struct node));
        p->data=t;
        p->left=p->right=NULL;
    }
    else
    {
        if(t<p->data)
        {
            p->left=in(t,p->left);
        }
        else if(t>p->data)
        {
            p->right=in(t,p->right);
        }
    }
    return p;
}
void preorder(tree p)//先序遍历
{
    if(p)
    {
        if(f) printf(" ");
        else f++;
        printf("%d",p->data);
        preorder(p->left);
        preorder(p->right);
    }
}
int main()
{
    int n,i,t;
    while(~scanf("%d",&n))
    {
        tree root=NULL;
        for(i=0;i<n;i++)
        {
            scanf("%d",&t);
            root=in(t,root);
        }
        f=0;
        preorder(root);
        printf("\n");
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/

posted @ 2015-04-19 09:49  xryz  阅读(109)  评论(0编辑  收藏  举报