这里是杭电hdu上的链接:http://acm.hdu.edu.cn/showproblem.php?pid=3999
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
解题思路:我的标题已经指出了这是水题,套用二叉搜索树的模板就行。另外在输出的时候注意空格即可,如果好几次没有ac的话可以参考下输出。
1 #include <iostream> 2 #include <cstdlib> 3 using namespace std; 4 5 int j; 6 7 struct node { 8 int val; 9 node *lch; 10 node *rch; 11 }; 12 13 node *creat (node *p, int x) { 14 if (p == NULL) { 15 node *q = new node; 16 q->val = x; 17 q->lch = q->rch = NULL; 18 return q; 19 } 20 else { 21 if (x < p->val) p->lch = creat (p->lch,x); 22 else p->rch = creat (p->rch,x); 23 return p; 24 } 25 } 26 void pre_order (node *s) { 27 //int j = 0;如果写这里--->每一次进来都是0 28 if (s) { 29 if (j > 0) 30 cout << " "; 31 j++; 32 cout << s->val; 33 pre_order (s->lch); 34 pre_order (s->rch); 35 } 36 } 37 38 int main() { 39 int n,x; 40 while (cin >> n) { 41 j = 0; 42 node *root = NULL; 43 for (int i = 0;i < n; ++i) { 44 cin >> x; 45 root = creat(root,x); 46 } 47 pre_order (root); 48 cout << endl; 49 } 50 return 0; 51 }
欢迎码友评论,一起成长。