九度OJ 1078
2016-05-31 21:51
211 查看
题目描述:
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
输入:
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
输出:
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
样例输入:
样例输出:
二叉树的先序中序后序遍历,大家都已经掌握了。这道题的意思是根据给定的先序中序,求出二叉树的后序遍历。
注意,已知二叉树的中序,以及先序后序中的一个,那么另一个的顺序就是确定的。
这里我们只要根据先序的第一个字母确定二叉树的根节点,然后在中序序列中找到该节点,那么在其左右分别是左右子树。然后在左右子树中进行递归操作即可。
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
输入:
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
输出:
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
样例输入:
ABC BAC FDXEAG XDEFAG
样例输出:
BCA XEDGAF
二叉树的先序中序后序遍历,大家都已经掌握了。这道题的意思是根据给定的先序中序,求出二叉树的后序遍历。
注意,已知二叉树的中序,以及先序后序中的一个,那么另一个的顺序就是确定的。
这里我们只要根据先序的第一个字母确定二叉树的根节点,然后在中序序列中找到该节点,那么在其左右分别是左右子树。然后在左右子树中进行递归操作即可。
#include <iostream> using namespace std; struct Node { Node *lchild; Node *rchild; char c; }Tree[50]; int loc; string str1,str2; Node *create(){ Tree[loc].lchild = Tree[loc].rchild = NULL; return &Tree[loc++]; } void postOrder(Node *T){ if(T->lchild!=NULL){ postOrder(T->lchild); } if(T->rchild!=NULL){ postOrder(T->rchild); } cout<<T->c; } Node *build(int s1,int s2,int e1,int e2){ Node *ret = create(); ret->c = str1[s1]; int rootIdx; for(int i=e1;i<=e2;i++){ if(str1[s1] == str2[i]){ rootIdx = i; break; } } if(rootIdx != e1){ ret->lchild = build(s1+1,s1+rootIdx-e1,e1,rootIdx-1); } if(rootIdx != e2){ ret->rchild = build(s1+rootIdx-e1+1,s2,rootIdx+1,e2); } return ret; } int main(){ while(cin>>str1){ cin>>str2; loc = 0; int l1 = str1.length(); int l2 = str2.length(); Node *T = build(0,l1-1,0,l2-1); postOrder(T); cout<<endl; } return 0; }
相关文章推荐
- 聊聊scrollview嵌套listview的问题
- dpkg命令的用法
- 记一次Nginx 400错误
- 任意凸多边形的面积
- oracle trunc()函数的使用方法
- Linux 默认目录结构
- 【web前端】input使用小结
- mysql常用函数
- 【java集合一】根接口Collection、Map
- Spring AOP 最终版实现
- 你会写“atoi”吗???
- 机器学习:从入门到沉迷
- C语言 面试
- Java IO - FileReader&FileWriter
- 排序项目模板
- 通讯录的录入与显示
- 使用mybatis的两种方式
- 解决ubuntu下的磁盘不能访问问题
- 用Workbench迁移MySQL小数据库
- Java使用ThreadFactory来创建新的线程