树的遍历---pat
来源:互联网 发布:淘宝卖快排配件犯法吗 编辑:程序博客网 时间:2024/06/06 02:48
树的遍历 (25分)
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数
NN
N(
≤30\le 30
≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
已知后序与中序输出前序(先序):
后序:3, 4, 2, 6, 5, 1(左右根)
中序:3, 2, 4, 1, 6, 5(左根右)
分析:因为后序的最后一个总是根结点,令i在中序中找到该根结点,则i把中序分为两部分,左边是左子树,右边是右子树。因为是输出先序(根左右),所以先打印出当前根结点,然后打印左子树,再打印右子树。左子树在后序中的根结点为root – (end – i + 1),即为当前根结点-右子树的个数。左子树在中序中的起始点start为start,末尾end点为i – 1.右子树的根结点为当前根结点的前一个结点root – 1,右子树的起始点start为i+1,末尾end点为end。
输出的前序应该为:1, 2, 3, 4, 5, 6(根左右)
#include<bits/stdc++.h>using namespace std ;struct node{ int va , pos ;}la[32];int main(){ queue<node> s; int mi[32] , re[32]; int n ; bool vis[32]; cin >> n ; if(n == 0) return 0 ; for(int i = 1 ; i <= n ; ++ i) cin >> la[i].va,la[i].pos=i; for(int i = 1 ; i <= n ; ++ i) cin >> mi[i],re[mi[i]]=i; memset(vis,0,sizeof(vis)); s.push(la[n]); int ans = 1 ; while(ans != n) { node ro = s.front(); s.pop(); int cnt = 0 ; vis[re[ro.va]] = true ; for(int i = re[ro.va]+1 ; i <= n ; i ++) { if(vis[i] || i > n) break ; cnt ++ ; } int cnt2 = 0 ; for(int i = re[ro.va]-1 ; i >= 0 ; i --) { if(vis[i] || i == 0) break ; cnt2 ++ ; } if(ro.pos-cnt-1 >= 1 && cnt2 != 0) s.push(la[ro.pos-cnt-1]); // 压入左树root if(ro.pos-1 >= 1 && cnt != 0) s.push(la[ro.pos-1]); // 压入右树root ans ++ ; printf("%d ",ro.va); } node last = s.front(); printf("%d\n",last.va); //printf("\n"); return 0 ;}
0 0
- 树的遍历---pat
- 树的遍历 PAT 1004
- pat -- 二叉树的遍历 (浙大的PAT)
- PAT L2-006. 树的遍历
- PAT L2-006. 树的遍历
- PAT L2-006. 树的遍历
- PAT L2-006. 树的遍历
- PAT L2-006 树的遍历
- 二叉树 三种遍历构造二叉树+层次遍历 题目 PAT 树的遍历
- PAT-4C-L2-006-树的遍历(DFS)
- PAT L2-006. 树的遍历(二叉树重构)
- PAT 树的遍历 1086. Tree Traversals Again
- 1004. Counting Leaves (30)-PAT甲级真题(bfs,dfs,树的遍历,层序遍历)
- **浙大PAT甲级 1086 二叉树的先中根遍历求后根遍历
- PAT 1020. Tree Traversals (25)(树的构造与遍历,通过后序中序输出层次遍历)
- pat 1004---简单的建树+层次遍历
- pat 1090,树的遍历,层序,先根遍历,利用缓存来优化,“以土地换和平”
- leetcode105 && leetcode106 && PAT 1138. 二叉树的三种遍历的应用
- C Toolkits for XML
- 京东2016研发工程师笔试题【年终奖】
- 【开发阶段】【调试】【跨域】【chrome】
- C. Anton and Fairy Tale
- java System.out.printf输出注意
- 树的遍历---pat
- tensorflow1.x版本rnn生成cell 报错解决方案
- java虚拟机理解(一)——内存模型与对象创建
- cas机制
- 文章标题
- ref和out的区别
- 316. Remove Duplicate Letters
- 【C# 计算代码的执行时间】
- JSON序列化(自定义对象,字典,数组的序列化)