题目描述:给你一颗二叉树的中序和后序遍历序列,请编程输出该二叉树左子树或右子树的后序遍历序列。
输入:
占三行,第一行表示二叉树的中序遍历序列,第二行表示后序遍历序列。用大写字母标识结点,二叉树的结点最多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);
}
}