数据结构实验之求二叉树后序遍历和层次遍历
来源:互联网 发布:知乎搞笑的事情 编辑:程序博客网 时间:2024/05/21 21:50
数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000MS Memory Limit: 65536KB
SubmitStatistic Discuss
Problem Description
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历和层序遍历。
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
Output
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列。
Example Input
2abdegcfdbgeafcxnliulnixu
Example Output
dgebfcaabcdefglinuxxnuli
Hint
注释写的很清楚,准备开始慢慢啃数据结构
#include <bits/stdc++.h>using namespace std;string a,b;struct node{ char data; node* lchild; node* rchild;};node* create(int l1,int r1,int l2,int r2){ if(l1>r1) return NULL; //先序遍历反复向右方移动以此来寻找根节点,当左边的大于右边时,停止遍历 node* root=new node; root->data=a[l1];//获取先序排列的根节点 int record; for(int i=l2;i<=r2;i++) { if(b[i]==a[l1]) { record=i; break; } } int numleft=record-l2;//通过中序遍历确定左树的数目 root->lchild=create(l1+1,l1+numleft,l2,record-1);//先序遍历只是负责提供根节点的,中序遍历负责区分左右树,然后把中序遍历确定的区间范围加到先序遍历上,完成dfs建树。 root->rchild=create(l1+numleft+1,r1,record+1,r2); return root;}void houxu(node* root){ if(root->lchild!=NULL) houxu(root->lchild); if(root->rchild!=NULL) houxu(root->rchild); cout<<root->data;}void bfs(node* root){ queue<node*> q; q.push(root); while(!q.empty()) { node* now=q.front(); q.pop(); cout<<now->data; if(now->lchild!=NULL) q.push(now->lchild); if(now->rchild!=NULL) q.push(now->rchild); }}int main(){ int n; cin>>n; getchar(); while(n--) { getline(cin,a); getline(cin,b); node* root=create(0,a.length()-1,0,b.length()-1); houxu(root); cout<<endl; bfs(root); cout<<endl; } return 0;}
阅读全文
0 0
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 超简单快速实现附件上传(各种格式文件)和下载显示(调用浏览器下载后选择可以打开的应用查看)
- 安卓学习日记 6-9 Rxjava
- Java锁机制--synchronized
- 启程了!在CSDN
- Android在webview下加载本地html的方式
- 数据结构实验之求二叉树后序遍历和层次遍历
- 项目2: 为CharityML寻找捐献者
- FATFS文件系统+源码分析——学习笔记
- MySQL添加用户、删除用户与授权
- Android Studio引入外部so的方法
- lnmp一键安装包搭建的环境,mysql在局域网内连接不上的问题
- C语言的内存分配calloc()函数
- Django学习笔记(二)
- web缓存(代理服务器)