博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hdu3999-The order of a Tree (二叉树的先序遍历)...
阅读量:5174 次
发布时间:2019-06-13

本文共 2374 字,大约阅读时间需要 7 分钟。

The order of a Tree

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 1361    Accepted Submission(s): 695

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

 

 

 

 

题解:题目意思即,给你一个插入数列,形成一棵二叉树,你给出字典序最小的插入方法建相同的一棵树出来。说白了,就是求先序序列。

代码:

1 #include 
2 #include
3 4 using namespace std; 5 6 typedef struct Node{ 7 Node *lch,*rch,*nex; 8 int x; 9 Node(int x){10 this->x=x;11 lch=NULL;12 rch=NULL;13 }14 }inode;15 16 int n,tn;17 inode *head;18 19 void insert(int t);20 void preOrder(inode *p);21 22 int main()23 {24 //freopen("D:\\input.in","r",stdin);25 //freopen("D:\\output.out","w",stdout);26 int t;27 while(~scanf("%d",&n)){28 scanf("%d",&t);29 head=new inode(t);30 for(int i=1;i
x)43 if(p->lch!=NULL) p=p->lch;44 else{45 p->lch=s;46 break;47 }48 else49 if(p->rch!=NULL) p=p->rch;50 else{51 p->rch=s;52 break;53 }54 }55 }56 void preOrder(inode *p){57 if(p!=NULL){58 printf("%d",p->x);59 if(++tn
lch);62 preOrder(p->rch);63 delete p;64 }65 }

转载于:https://www.cnblogs.com/jiu0821/p/4634657.html

你可能感兴趣的文章
Vue: 常用指令
查看>>
简单介绍.Net3.0 中跨线程访问控件
查看>>
oracle imp 工具可能出现的问题
查看>>
bzoj1045题解
查看>>
学习Cocos2d的博客 --推荐
查看>>
SpringMVC中@RequestMapping参数设置
查看>>
lea实现加法
查看>>
文件操作
查看>>
spring容器启动的加载过程(三)
查看>>
java之接口适配器
查看>>
nginx安装手册
查看>>
Find Backpacker Jobs in Australia
查看>>
面试题:return和finally执行
查看>>
Heroku第三方服务接入指南(二)
查看>>
MSRA专访摘要
查看>>
团队作业4
查看>>
第四次团队作业--选题
查看>>
记录专用
查看>>
一句实现jquery导航栏
查看>>
场景分析:用户登录界面场景分析
查看>>