二叉树的序遍历

来源:互联网 发布:淘宝金牌店铺联盟 编辑:程序博客网 时间:2024/06/05 06:07

二叉树的序遍历

http://codevs.cn/problem/3143/ 二叉树的序遍历.模板题

#include<iostream>#include<cstring>#include<cstdio>using namespace std;const int maxn = 1010;struct point{    int l,r;}p[maxn];void build(int l,int r,int x){    p[x]=(point){l,r};}void first(int s)//根->左->右 {    if(!s)    return;    printf("%d ",s);    first(p[s].l);    first(p[s].r);}void mid(int s)//左->根->右 {    if(!s)    return;    mid(p[s].l);    printf("%d ",s);    mid(p[s].r);}void nxt(int s)//左->右->根 {    if(!s)    return;    nxt(p[s].l);    nxt(p[s].r);    printf("%d ",s);}int main(){    int n,a,b;    scanf("%d",&n);    for(int i=1;i<=n;i++)    {         scanf("%d%d",&a,&b);         build(a,b,i);    }    first(1);puts("");    mid(1);puts("");    nxt(1);    return 0;}


http://codevs.cn/problem/2010/已知前序·中序遍历,求后序遍历
利用好前序遍历与中序遍历的性质,DFS求解

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>#include<cmath>using namespace std;char first[10010],mid[10010];void solve(int k,int l,int r){    if(l==r)    return;    int pos=l;    for(int i=l;i<=r;i++)//前序遍历的每一个树/子树的第一个点为根节点,从中序遍历中标记相应位置     {                   //中序遍历中(以下皆为中序遍历顺序)在这之前的点集为左子树范围,之后为右子树范围         if(mid[i]==first[k])        {            pos=i;            break;        }    }    solve(k+1,l,pos);//k+1:下一左子树第一个节点的顺序位置     solve(k+pos-l+1,pos+1,r);//k+pos-l+1:下一右子树第一个节点的位置(根节点位置),k+pos-l为左子树最后一个节点的位置     printf("%c",first[k]);//后序遍历输出 }int main(){    scanf("%s%s",&first,&mid);    solve(0,0,strlen(first));    return 0;}
原创粉丝点击