数据结构实验之求二叉树后序遍历和层次遍历
2016-04-13 21:50
176 查看
数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
输出
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列
示例输入
2 abdegcf dbgeafc xnliu lnixu
示例输出
dgebfca abcdefg linux xnuli
提示
#include <stdio.h> #include <string.h> #include <stdlib.h> struct node { char data; struct node *l, *r; }; struct node * creat(char *s1,char *s2, int len) { if(len <=0){ return NULL; } struct node *root; root = (struct node *)malloc(sizeof(struct node)); root->data = *s1; char *p; for(p = s2;;p++){ if(*p == *s1){ break; } } int k = p-s2; root->l = creat(s1+1,s2,k); root->r = creat(s1+k+1,p+1,len-k-1); return root; } void three(struct node *tree) { if(tree){ three(tree->l); three(tree->r); printf("%c", tree->data); } } void seque(struct node *tree) { struct node *q[100]; int head = 0; int tail = 1; q[head] = tree; while(head < tail){ if(q[head]!=NULL){ printf("%c", q[head]->data); q[tail++] = q[head]->l; q[tail++] = q[head]->r; } head++; } } int main() { int t; while(~scanf("%d", &t)){ char s1[100]; char s2[100]; struct node *tree; while(~scanf("%s %s", s1, s2)){ int len = strlen(s1); tree = creat(s1,s2,len); three(tree); printf("\n"); seque(tree); printf("\n"); } } return 0; }
相关文章推荐
- 数据结构实验之二叉树四:还原二叉树
- Huffman树的简单实现
- 数据结构中八大排序算法
- 用于并行计算的多线程数据结构,第 2 部分: 设计不使用互斥锁的并发数据结构
- 用于并行计算的多线程数据结构,第 1 部分: 设计并发数据结构
- 栈的数组表示
- 从键盘读入n个整数(升序),请编写算法实现: 建立带表头结点的单链表; 显示单链表,(形如:H->10->20->30->40); 在有序单链表中插入新的数据元素x; 将单链表就地逆
- C语言实现的数据结构之------哈希表
- LRU Cache数据结构
- Java数据结构——哈希表
- YTUOJ之逆序输出单词(串)
- HDU 4411最小费用流
- 考研中的算法时间复杂度求解
- java中的数据结构
- 数据结构图的运算(深度优先)
- 数据结构与算法-第12章二叉树和其他树-001遍历集合的所有子集
- linux内核数据结构之kfifo(实现)
- 数据结构(java)——栈及其应用
- ThreadLocal
- 数据结构和算法05 之红-黑树(看完包懂~)