pat考试-1138

  1. Postorder Traversal (25)
    时间限制
    600 ms
    内存限制
    65536 kB
    代码长度限制
    16000 B
    判题程序
    Standard
    作者
    CHEN, Yue
    Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=50000), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.

Sample Input:
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
Sample Output:
3

这个题,真正看出我写代码的能力,老师讲过的,只是没讲怎么实现,自己就不会实现了,太菜了。。。
已知前序和中序求后序;
可根据思路:第一步:根据前序可知根节点为1;第二步:根据中序可知2 3为根节点1的左子树和5 4 7 6为根节点1的右子树;第三步:递归实现,把2 3当做新的一棵树和5 4 7 6也当做新的一棵树;第四步:在递归的过程中输出后序。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 50004;
int a[N],b[N];
int n;
bool flag = false;
//递归地分左子树和右子树,p为前序遍历的起始点
//p代表的是该子树的前序起点,q代表的是中序起点,m代表的是子树的长度
void dfs(int p,int q,int m)
{
    /*if(flag){
        return;
    }*/
    //这儿是输出叶子节点
    if(m == 1){
        printf("%d ",a[p]);
        /*flag = true;*/
        return;
    }
    if(m <= 0){
        return ;
    }
    int root = q;
    for(int i = q;i <= q + m;++i)
    {
        if(a[p] == b[i]){
            root = i;
            break;
        }
    }
    // << p << " " << root << endl;
    //cout << p + 1 << " " << q << " " << root - q << endl;
    //cout << p + root - q + 1 << " " << q + root - q + 1 << " " << m - root + q - 1 << endl;
    dfs(p + 1,q,root - q);
    dfs(p + root - q + 1,q + root - q + 1,m - root + q - 1);
    //这儿输出根节点
    printf("%d ",a[p]);
}
int main()
{
    scanf("%d",&n);
    for(int i = 0;i < n;++i)
    {
        scanf("%d",&a[i]);
    }
    for(int i = 0;i < n;++i)
    {
        scanf("%d",&b[i]);
    }
    dfs(0,0,n);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值