树的遍历专讲(知二求一)
来源:互联网 发布:unity3d 骨骼动画制作 编辑:程序博客网 时间:2024/05/29 08:50
今天,我们将对树形结构中知二求一的问题模型展开探究,但不包括不知道中序遍历。
1.先序中序求后序。
给大家一组样例:
入:
ABCD
BADC
出:
BDCA
大家可以仔细分析,得出这样一个结论,先找先序的第一个,然后第二个,第三个……一个个的加入树,最终输出,所以程序就出来了
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<math.h>#include<iostream>using namespace std;typedef struct node;typedef node *tree;struct node{ char date; tree lchild,rchild;};tree t;char s[101],s1[101];int pos(char c,int k,int j){ for(int i=k;i<=j;i++) if(c==s[i])return i; return -1;}int len;void haveatree(tree &bt,int l,int r){ if(l>r || len==strlen(s)){ bt=NULL; return; } int p=pos(s1[len],l,r); if(p==-1){ bt=NULL; return; } bt=new node; bt->date=s[p]; len++; haveatree(bt->lchild,l,p-1); haveatree(bt->rchild,p+1,r);} void preorder(tree bt){ if(bt){ printf("%c",bt->date); preorder(bt->lchild); preorder(bt->rchild); }}void postorder(tree bt){ if(bt){ postorder(bt->lchild); postorder(bt->rchild); printf("%c",bt->date); }}int main(){ int i,j,k,n,m; gets(s1);gets(s); len=0; haveatree(t,0,strlen(s)-1); postorder(t);puts(""); return 0;}
2.中序后序求先序。
同样给出一组样例:
入:
BADC
BDCA
出:
ABCD
这里只要将对先序遍历的处理倒着来,就OK了(^o^)/~,代码如下:
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<math.h>#include<iostream>using namespace std;typedef struct node;typedef node *tree;struct node{ char date; tree lchild,rchild;};tree t;char s[101],s1[101];int pos(char c,int k,int j){ for(int i=k;i<=j;i++) if(c==s[i])return i; return -1;}int len;void haveatree(tree &bt,int l,int r){ if(l>r || !len){ bt=NULL; return; } int p=pos(s1[len-1],l,r); if(p==-1){ bt=NULL; return; } bt=new node; bt->date=s[p]; len--; haveatree(bt->rchild,p+1,r); haveatree(bt->lchild,l,p-1);} void preorder(tree bt){ if(bt){ printf("%c",bt->date); preorder(bt->lchild); preorder(bt->rchild); }}int main(){ int i,j,k,n,m; gets(s);gets(s1); len=strlen(s1); haveatree(t,0,strlen(s)-1); preorder(t);puts(""); return 0;}
这是一个神奇的小股市(故事)!!!
本来ljf想要写一个地柜(递归)的小程序,可是……
所以,就陷入了市二附中(始而复终)的无限循环! I hurt you in invisibly
1 0
- 树的遍历专讲(知二求一)
- 二叉树遍历 小讲
- 数据结构 第12讲 二叉树的层次遍历
- 第五讲 树-1(广度优先遍历二叉树&深度优先遍历二叉树)
- Set的遍历以及排序详讲
- Set的遍历以及排序详讲
- 二叉树的遍历(层遍历和深度遍历)
- 二叉树的遍历(递归遍历)
- OC基础第5讲)字典类 {集合类 数组,字典,集合的快速遍历 数组排序}
- 树的前序遍历,中序遍历,后序遍历,层次(广度)遍历
- 二叉树的遍历(1)--先序遍历,中序遍历,后序遍历
- 二叉树的遍历(前序遍历、中序遍历、后序遍历)
- 二叉树的遍历代码(先序遍历,中序遍历,后序遍历)
- 【数据结构与算法】二叉树的遍历(递归遍历、非递归遍历、层序遍历)
- 二叉树的建立及遍历(先序遍历、中序遍历、后续遍历、层次遍历)
- 树的遍历(递归)
- 树的遍历(个人版)
- 二叉树的遍历 (二叉树遍历转换)
- poj The Unique MST 次小生成树(入门级)
- UVA10325:The Lottery (容斥)
- light oj 1245 1245
- 阿里的笔试,正则表达式
- 简单Web项目 struts + hibernate
- 树的遍历专讲(知二求一)
- LeetCoder 6. ZigZag Conversion
- 算法训练 一元三次方程求解 二分
- ADO.NET 快速入门(一):ADO.NET 概述
- ALGO137——Lift and Throw
- HDU 5324 分治
- Angular控制器知识点总结
- mongodb介绍及基本操作
- HTTP的请求方法OPTIONS