SDUT 2137 数据结构实验之求二叉树后序遍历和层次遍历
2015-06-10 21:11
405 查看
**数据结构实验之求二叉树后序遍历和层次遍历**
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
输出
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列
示例输入
2
abdegcf
dbgeafc
xnliu
lnixu
示例输出
dgebfca
abcdefg
linux
xnuli
代码::
#include <bits/stdc++.h> using namespace std; struct node { int data; node *l,*r; }*q[110]; struct node *creat(char *s,char *a,int len) { if(len <= 0) return NULL; node *head = new node; head->l = NULL; head->r = NULL; head->data = *s; int p = strchr(a,*s) - a; head->l = creat(s+1,a,p); head->r = creat(s+p+1,a+1+p,len-p-1); return head; } void post(node *head) { if(head) { post(head->l); post(head->r); printf("%c",head->data); } } void cenci(node *head) { int e = 0; int s = 0; q[s++] = head; while(s > e) { head = q[e++]; printf("%c",head->data); if(head->l) q[s++] = head->l; if(head->r) q[s++] = head->r; } } int main() { std::ios::sync_with_stdio(false); int n; char s[51],a[51]; while(cin>>n) { while(n--) { cin>>s>>a; int len = strlen(s); node *head = creat(s,a,len); post(head); printf("\n"); cenci(head); printf("\n"); } } return 0; }
相关文章推荐
- BZOJ 4085:[Sdoi2015]quality(round 2 音质检测)(数据结构)
- MySQL索引背后的数据结构及算法原理
- 数据结构实验图论一:基于邻接矩阵的广度优先搜索遍历
- leetcode--Binary Tree Inorder Traversal
- Codeforces Round #306 (Div. 2) D.E. 解题报告
- Json数据结构
- XML、JSON数据结构解析
- 大话数据结构—多路查找树(B树)
- RDP协议详解
- 数据结构(二)---栈:
- JAVA数据结构之String、StringBuffer和StringBuilder之间的区别
- 数据结构
- 数据结构——算法之(043)(c++各种排序算法实现)
- 数据结构——算法之(042)(字符串移位包含的问题, s1是否可以由s2移位后得到)
- 数据结构——算法之(041)(寻找数组中的最大值和最小值)
- 数据结构——算法之(040)(最大公约数问题)
- 数据结构----图(邻接表用法)
- 数据结构——算法之(039)(ip合法性检查)
- 数据结构与算法-求子数组的最大和
- 数据结构与算法-设计包含min函数的栈