The Postorder enumeration(二叉树遍历:前中转后)

本文介绍了一种通过前序和中序遍历确定二叉树后序遍历的方法,并提供了一个C++实现示例。该算法适用于不同元素组成的二叉树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目描述】

Give you the Preorder enumeration and Inorder enumeration of a binary tree, output its Postorder enumeration. We assume the elements of binary tree are different.

【输入要求】

The first line contains the number of test cases, N.
In each tese case, the first line is the Preorder enumeration and the second line is Inorder enumeration.

1
ABDCEGFHI
BDAGECHFI

【输出要求】

Out put N lines. Each line represent the Postorder enumeration

DBGEHIFCA
【我的程序】

#include <iostream>
#include <string>
using namespace std;

int index;
string qian,zhong;

void enumeration(int x, int y)
{
    if (x>y) return;
    char root=qian[index++];
    int pos=zhong.find(root,x);
    enumeration(x,pos-1);
    enumeration(pos+1,y);
    cout<< root;
}

int main()
{
    int n;
    cin>> n;
    cin.get();
    for (int i=0;i<n;i++)
    {
        index=0;
        getline(cin,qian);
        getline(cin,zhong);
        enumeration(0,zhong.length()-1);
        cout<< endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值