这里是杭电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的话可以参考下输出。
 #include <iostream>
#include <cstdlib>
using namespace std; int j; struct node {
int val;
node *lch;
node *rch;
}; node *creat (node *p, int x) {
if (p == NULL) {
node *q = new node;
q->val = x;
q->lch = q->rch = NULL;
return q;
}
else {
if (x < p->val) p->lch = creat (p->lch,x);
else p->rch = creat (p->rch,x);
return p;
}
}
void pre_order (node *s) {
//int j = 0;如果写这里--->每一次进来都是0
if (s) {
if (j > )
cout << " ";
j++;
cout << s->val;
pre_order (s->lch);
pre_order (s->rch);
}
} int main() {
int n,x;
while (cin >> n) {
j = ;
node *root = NULL;
for (int i = ;i < n; ++i) {
cin >> x;
root = creat(root,x);
}
pre_order (root);
cout << endl;
}
return ;
}

  欢迎码友评论,一起成长。

最新文章

  1. Shell命令_smem
  2. poj 2594 传递闭包+最大路径覆盖
  3. sql 中各种锁随记
  4. LeetCode Search a 2D Matrix II (技巧)
  5. 函数buf_page_init_for_read
  6. [JavaScript] js 迅雷评分效果
  7. Div+css中ul ol li dl dt dd使用
  8. mysql启动停止,一台服务器跑 多个mysql数据库
  9. barManager.Menu(barSubItem)
  10. Phone APP设计规范/iPad APP设计规范/Android APP设计规范/网页设计规范
  11. Spring MVC执行流程
  12. 六大设计原则(一)SRP单一职责原则
  13. Redirection
  14. 双跑道------js分机号
  15. 小程序 input 键盘弹出时样式遮盖问题
  16. CTSC被虐记
  17. chrome浏览器直接编辑源码功能的开通办法 - Chrome Workspace
  18. python中的List 和 Tuple
  19. VC被控制时关闭极域电子教室、破解联想硬盘保护系统密码(上)
  20. spring中事务配置

热门文章

  1. 5款最好用的开源Web快速开发工具
  2. Bitmap的读写
  3. asp.net MVC 路由机制 Route
  4. 部署开启了Kerberos身份验证的大数据平台集群外客户端
  5. 数据库中的null问题
  6. windows环境下解决web服务假死的问题
  7. [ios2]iphone编程中使用封装的NSLog来打印调试信息 【转】
  8. ORACLE查询语句
  9. JQuery动态操作表格
  10. android 轮播图