由中序和后序遍历来确定前序遍历

题目描述:给你一颗二叉树的中序和后序遍历序列,请编程输出该二叉树左子树或右子树的后序遍历序列。

输入:

占三行,第一行表示二叉树的中序遍历序列,第二行表示后序遍历序列。用大写字母标识结点,二叉树的结点最多26个。
第三行是单个字母,L表示要求输出该二叉树的左子树的后序遍历序列,R表示要求输出该二叉树的右子树的后序遍历序列。

输出:

按要求输出该二叉树左子树或右子树的后序遍历序列。

样例输入:

BDCEAFHG
DECBHGFA
R
样例输出:

HGF
 

#include<iostream>

#include<vector>

#include<string>

#include<algorithm>

using namespace std;

string mid;

string last;

struct Node

{

    Node *lchild;

    Node *rchild;

    char data;

};

void lastorder(Node *root)

{

    if(root==NULL) return;

    else

    {

        lastorder(root->lchild);

        lastorder(root->rchild);

        cout<<root->data;

    }

}

Node *create(int midl,int midr,int lastl,int lastr)

{

    if(lastl>lastr) return NULL;

    Node*root=new Node;

    root->data=last[lastr];

    int k;

    for(k=midl;k<midr;k++)

    {

        if(root->data==mid[k])

        {

            break;

        }

    }

    //k=4;

    int len=k-midl;

    root->lchild=create(midl,k-1,lastl,lastl+len-1);

    root->rchild=create(k+1,midr,lastl+len,lastr-1);

    return root;

}

int main()

{

    cin>>mid>>last;

    Node*root=create(0,mid.size()-1,0,last.size()-1);

    char m;

    cin>>m;

    if(m=='R')

    {

        lastorder(root->rchild);

    }

    else {

    lastorder(root->lchild);

    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值