已知树的先中序遍历--不建树--得到层序遍历
2016-06-22 10:24
351 查看
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> using namespace std; int Count=0; struct Node { int num; int lawyer; }; Node Floor[20]; bool cmp(struct Node a,struct Node b) { return a.lawyer<b.lawyer; } void PreIn_Floor(Node* Pre,Node* In,int len,int lawyer); void Sort(Node* Floor,int N); int main() { Node Pre[20],In[20]; int N; cin >> N; for(int i=0; i<N; i++) scanf("%d",&In[i].num); for(int i=0; i<N; i++) scanf("%d",&Pre[i].num); PreIn_Floor(Pre,In,N,1); /* 打印看看排序前是什么结果 for(int i=0; i<N; i++) cout << Floor[i].num << " "; cout << endl; for(int i=0; i<N; i++) cout << Floor[i].lawyer << " " ; cout << endl; */ sort(Floor,Floor+N,cmp); for(int i=0; i<N; i++) cout << Floor[i].num << " " ; return 0; } void PreIn_Floor(Node* Pre,Node* In,int len,int lawyer) { if( len==0 )//递归的退出条件 return ; int i=-1; while( (*Pre).num != In[++i].num ) ; //思考为什么这样不会是一个死循环,也就是说一定会找到 Floor[Count].num = (*Pre).num;//每一次递归进行的操作 Floor[Count].lawyer = lawyer; Count++; PreIn_Floor( Pre+1,In,i,lawyer+1 );//递归左子树 PreIn_Floor( Pre+1+i,In+1+i,len-i-1,lawyer+1 );//递归右子树 } /** 测试样例: 10 1 2 4 8 5 9 10 3 6 7 8 4 2 5 10 9 1 6 3 7 */
相关文章推荐
- [置顶] 开源项目XXL-JOB源码的导入及在eclipse下的配置
- leetcode(3)remove-duplicates-from-sorted-array
- axure7.0 --下载、安装、汉化记录
- 排序算法系列--冒泡泡泡(C++)
- shell --- 相关简单程序规整
- 如何分析解决Android ANR
- 2003求绝对值
- C++之new
- MySQL常用聚合函数
- js实现a标签超链接提交form表单的方法
- 安卓开发:提升ListView的运行效率
- awk截取字符串 权限
- webservice的远程调用方法
- Java的JSON转换库GSON的基本使用方法示例
- Json解析的方法小结
- 解释DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
- 【重大更新】MFC用户界面套包BCGControlBar Pro for MFC发布v25.0|附下载
- Lua的元方法__newindex元方法
- 2002计算球体积
- vs配置:调试状态的web.config配置