求二叉树的先序遍历--知中序和后序求前序
来源:互联网 发布:湖南省软件协会 编辑:程序博客网 时间:2024/06/01 09:48
求二叉树的先序遍历
题目描述
已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的中序遍历序列,第二个字符串表示二叉树的后序遍历序列。
输出
输出二叉树的先序遍历序列
示例输入
2dbgeafcdgebfcalnixulinux
示例输出
abdegcfxnliu
#include <bits/stdc++.h> using namespace std; typedef struct node { char data; struct node *l,*r; } tree; tree *creat(int len,char *in,char *last) /*中序遍历中根节点的左边全都是左子树的中序, 右边全是右子树中序。然而每个子树的先序序列的第一个节点是 子树的根,而且向后移动中序查找得到的左子树节点数便可分开 得到左右子树。因此可以用递归分而治之*/ { tree *head; //创立根节点 if(len==0) { return NULL; //节点为零时,表示数据完全进入树中 } head=new node; char *p; head->data=last[len-1]; //先序的第一个节点指定是当前子树的根 for(p=in; p!=NULL; p++) if(*p==last[len-1]) break; int lon=p-in; //左子树节点的个数 head->l=creat(lon,in,last); //分而治之创建左子树 head->r=creat(len-lon-1,p+1,last+lon); //分而治之创建右子树 return head; } void pre(tree * root) { if(root) { printf("%c",root->data); pre(root->l); pre(root->r); } } int main() { int n; char s0[1000],s1[1000]; scanf("%d",&n); getchar(); while(n--) { scanf("%s",s0); scanf("%s",s1); char *in,*last; in=s0; last=s1; int len=strlen(s1); //节点数 tree *root=creat(len,in,last); //从两个字符串中找到树 pre (root); //后序遍历 puts(""); } return 0; }
0 0
- 求二叉树的先序遍历--知中序和后序求前序
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 求二叉树的先序遍历
- 传说中的数据结构 SDUT 2556
- bootstrap3 char.js 使用
- 调试Bug的神兵利器:通过WinDbg条件断点收集Log
- 互联网的发展关键词:连接——集合器与过滤器?
- 【Mockplus教程】安装Mockplus
- 求二叉树的先序遍历--知中序和后序求前序
- NBUT 1218 You are my brother
- C语言之文件操作04——输入矩阵a,b,求乘积c,并打印a,b,c到文件
- jquery实现选项在两个下拉列表之间选择性移动的功能
- 如何将VirtualBox和VMware虚拟机相互转换
- No such file or directory (/Users/appleapple/Library/Developer/Xcode/DerivedData/
- 数学1A - Power of Cryptography
- R语言之描述性统计量
- fastCGI 攻击