The order of a Tree
Problem Description
As we know,the shape of a binary search tree is greatly related to the order of keys we insert. To be precisely:
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
There are multiple test cases in an input file. The first line of each testcase is an integer n(n <= 100,000),represent the number of nodes.The second line has n intergers,k1 to kn,represent the order of a tree.To make if more simple, k1 to kn is a sequence of 1 to n.
Output
One line with n intergers, which are the order of a tree that generate the same tree with the least lexicographic.
Sample Input
4
1 3 4 2
Sample Output
1 3 2 4
题意:如果树为空,则插入的第一个数为根
如果树不为空,则小于根的插入到它的左子树,否则插入到右子树
#include <iostream>
using namespace std;
typedef struct tree_Node{
int data;
struct tree_Node *lchild, *rchild;
tree_Node(){ lchild = rchild = NULL; }
}*tree;
void dlr(tree t, bool flag)
{
if(t != NULL)
{
if(flag)
cout<<t->data;
else
cout<<" "<<t->data;
dlr(t->lchild, false);
dlr(t->rchild, false);
}
}
void insert(int data, tree &t)
{
if(t == NULL)
{
t = new tree_Node();
t->data = data;
return;
}
if(t->data > data)
insert(data, t->lchild);
else
insert(data, t->rchild);
}
void destory(tree t)
{
if(t != NULL)
{
destory(t->lchild);
destory(t->rchild);
delete t;
}
}
int main()
{
int i, n, data;
while(cin>>n)
{
tree t = NULL;
for(i = 0; i < n; i++)
{
cin>>data;
insert(data, t); //插入数据
}
dlr(t, true); //先序遍历
destory(t); //释放内存
cout<<endl;
}
return 0;
}