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;
}
分享到:
相关推荐
Hdu 3333解题报告 题意描述: 给你n个数现在要你求在k个区间上[ai, bi]的不相同的数之和各是多少. N,000; k,000; 显然,这题不能用暴力来做。 这题我们选择用线段数来做。
The least common multiple (LCM) of a set of positive integers is the smallest positive integer which is divisible by all the numbers in the set. For example, the LCM of 5, 7 and 15 is 105. Input Input...
For a positive integer n, let’s denote function f(n,m) as the m-th smallest integer x that x>n and gcd(x,n)=1. For example, f(5,1)=6 and f(5,5)=11. You are given the value of m and (f(n,m)?n)⊕n,...
acm hdu as easy as a+b
HDU的1250,主要是利用高精度加法,但是代码有点繁琐,效率不是很高
杭电ACMhdu1163
hdu1001解题报告
HDU1059的代码
hdu 1574 passed sorce
HDU的一题........HDU DP动态规
hdu2101AC代码
hdu acm 教案 搜索入门 hdu acm 教案 搜索入门
搜索 dfs 解题代码 hdu1241
hdu 5007 Post Robot 字符串枚举。 暴力一下就可以了。
hdu acm 教案 动态规划(1) hdu acm 教案 动态规划(1)
hdu_2102_passed_sorce
自己做的HDU ACM已经AC的题目
hdu 1166线段树代码
HDU最全ac代码
hdu动态规划算法集锦