hdu 1710 Binary Tree Traversals(二叉树:前中求后)

前:1 2 4 7 3 5 8 9 6 pre[]
中:4 7 2 1 8 5 9 3 6 in[]

l , r 分别对应中序列(int[])的首地址和尾地址
i 对应中序遍历中的根结点
rt 对应前序遍历中的根结点
后序遍历(lrv)

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
using namespace std;
const int N=1007,INF=0x3f3f3f3f;
int in[N],pre[N];
int n,k;
void dfs(int l,int r,int rt)
{
    int i;
    for(i=l;in[i]!=pre[rt];i++);//in[i]==pre[rt]时结束循环
    if(l<=i-1) dfs(l,i-1,rt+1);//左子树
    if(i+1<=r) dfs(i+1,r,rt+i-l+1);//右子树
    k==0?printf("%d",in[i]):printf(" %d",in[i]),k++;//输出(lrv)
}
int main()
{

    while(~scanf("%d",&n))
    {
        k=0;
        for(int i=1;i<=n;i++)
            scanf("%d",&pre[i]);
        for(int i=1;i<=n;i++)
            scanf("%d",&in[i]);
        dfs(1,n,1);//直接传入地址便可
        puts("");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值