树的遍历专讲(知二求一)

来源:互联网 发布: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;}

Created with Raphaël 2.1.0gjhgjhljfljfzouzhenzouzhen李四李四嘿,ljf, 写博客了没?ljf愣了一下,想:忙得吐血,哪有时间写。gjh看看ljf网络流做完了没?你们这些大智障你是谁?你们好恶心。

这是一个神奇的小股市(故事)!!!
本来ljf想要写一个地柜(递归)的小程序,可是……

Created with Raphaël 2.1.0开始ljf装逼ljf是人结束yesno

所以,就陷入了市二附中(始而复终)的无限循环!
I hurt you in invisibly

1 0
原创粉丝点击