The order of a Tree
Problem Description
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.
Input
Output
Sample Input
4 1 3 4 2
Sample Output
1 3 2 4
一道關於二叉搜索樹的題目,要使其爲最小字典序 ,
那麼只要先把其建成一顆二叉搜索樹,然後根據其特點,
左小右大,然後用先序遍歷即可輸出最小字典序序列;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
struct Tree
{
Tree *l,*r; //建立樹的左右子樹
int x; //結點值
};
Tree *gen; //定義樹
Tree *jian(Tree *rt,int x) //建樹
{
if(rt==NULL) //根
{
rt=(Tree *)malloc(sizeof(Tree)); //該結點是樹根,則新開闢個結點,讓其爲根結點
rt->x=x;
rt->l=rt->r=NULL; //左右子樹爲空
return rt;
}
if(rt->x>x) //如果當前的值小於結點的值,那麼進入左子樹
{
rt->l=jian(rt->l,x);
}
else rt->r=jian(rt->r,x); //如果當前的值大於結點的值,那麼進入左右子樹
return rt;
}
void bianli(Tree *rt,int x) //遍歷
{
if(x==1)
{
cout<<rt->x;
}
else cout<<" "<<rt->x;
if(rt->l!=NULL) bianli(rt->l,2); //如果左子樹不爲空
if(rt->r!=NULL) bianli(rt->r,2);//如果右子樹不爲空
}
int main()
{
int n,x;
while(cin>>n)
{
gen=NULL;
for(int i=0;i<n;i++)
{
cin>>x;
gen=jian(gen,x);
}
bianli(gen,1);
cout<<endl;
}
return 0;
}