1. insert a key k to a empty tree, then the tree become a tree with
only one node;
2. insert a key k to a nonempty tree, if k is less than the root ,insert
it to the left sub-tree;else insert k to the right sub-tree.
We call the order of keys we insert “the order of a tree”,your task is,given a oder of a tree, find the order of a tree with the least lexicographic order that generate the same tree.Two trees are the same if and only if they have the same shape.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
int n;
struct node *l,*r;
}BT;
BT* ct(BT *p,int n)//建树
{
if(p==NULL)
{
p=(BT*)malloc(sizeof(BT));
p->n=n;
p->l=p->r=NULL;
return p;
}
if(p->n>n)
p->l=ct(p->l,n);
else
p->r=ct(p->r,n);
return p;
}
void ds(BT *p,int c)//前序遍历
{
if(c!=1)
printf(" %d",p->n);
else
printf("%d",p->n);
if(p->l!=NULL)
ds(p->l,2);
if(p->r!=NULL)
ds(p->r,2);
}
int main()
{
int i,n,m;
BT *p=NULL;
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++)
{
scanf("%d",&m);p=ct(p,m);
}
ds(p,1);printf("\n");
}
return 0;
}
------江财小子