博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SDUT 2137 数据结构实验之求二叉树后序遍历和层次遍历
阅读量:6887 次
发布时间:2019-06-27

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

 

数据结构实验之求二叉树后序遍历和层次遍历

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

 已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历和层序遍历。

Input

 输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。

Output

每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列。

Sample Input

2abdegcfdbgeafcxnliulnixu

Sample Output

dgebfcaabcdefglinuxxnuli 提示:本题用到了还原二叉树的知识点,即通过前序+中序来还原二叉树,从而输出它的后序遍历和层序遍历。 代码实现如下(g++):
#include 
using namespace std;typedef struct node{ char data; struct node *left; struct node *right;} node;//typedef定义struct node结构体node *create(int n,char *a,char *b){ node *root; char *p;//定义一个指针,用来查找b数组 if(n==0) return NULL;//如果n==0,即长度为空,不存在 root=(node *)malloc(sizeof(node));//申请空间 root->data=a[0];//注意a数组是前序遍历,所以它的第一个元素必定是该树的根节点 for(p=b; p!='\0'; p++) { if(*p==a[0])//一步步找b数组中a[0]的位置,找到位置记下来 break; } int t=p-b;//左子树长度为p-b root->left=create(t,a+1,b);//三个变量分别为左子树长度,指向a的下一位,指向b root->right=create(n-t-1,a+t+1,p+1);//三个变量分别为右子树长度,指向a+左子树长度+根节点长度,指向p的下一位 return root;}void housort(node *root)//后序遍历{ if(root) { housort(root->left);//遍历左儿子 housort(root->right);//遍历右儿子 cout<
data;//遍历根节点,输出根节点 }}void cengci(node *root)//层序遍历,需要用到队列{ queue
t; t.push(root); while(!t.empty()) { root=t.front(); t.pop(); if(root) { cout<
data; t.push(root->left); t.push(root->right);//将左右节点依次进队,先进先出,很好理解 } }}int main(){ char a[55],b[55]; int n; while(~scanf("%d",&n)) { node *root; scanf("%s",a); scanf("%s",b); n=strlen(a); root=create(n,a,b); housort(root); printf("\n"); cengci(root); printf("\n"); } return 0;}/***************************************************Result: AcceptedTake time: 0msTake Memory: 200KB****************************************************/

 

转载于:https://www.cnblogs.com/jkxsz2333/p/9498627.html

你可能感兴趣的文章
C# 利用性能计数器监控网络状态
查看>>
网络对抗技术作业一
查看>>
最短路(Floyd_Warshall) POJ 2240 Arbitrage
查看>>
select2使用
查看>>
POJ1816:Wild Words——题解
查看>>
12.使用default-Action配置统一访问
查看>>
mysql建表---级联删除
查看>>
分布式队列神器 Celery
查看>>
windows 允许其他电脑访问本地mysql数据库
查看>>
.Net进阶系列(21)-跨域请求
查看>>
标准输入的EOF
查看>>
如何使用Git命令将项目从github或者服务器上克隆下来
查看>>
cplusplus.com
查看>>
svg了解一下
查看>>
使用slidingmeu_actionbarsherlock_lib的问题和The hierarchy of the type MainActivity is inconsistent...
查看>>
VS2015新功能
查看>>
数组、ArrayList、List<T>区别和选择
查看>>
使用MVC Razor生成格式良好的HTML Body作为邮件内容
查看>>
扑克游戏 模拟赛C组
查看>>
JUnit4 中@AfterClass @BeforeClass @after @before的区别对比
查看>>