先构建二叉树,后进行中序遍历
1.后序的最后一个节点是二叉树的根节点,即前序遍历的第一个节点,找到其在中序遍历中的位置,分为做字数和右子树两部分
A
/ \
CBH DE
2.左子树中的节点在后序遍历中位于最右边的节点是当前根节点,找到其在中序遍历中的位置,以此类推,分别找到左子树和右子树
A
/ \
B D
/ \ \
C H E
所以前序遍历结果是:ABCHDE
#include <iostream>
#include <string>
using namespace std;
typedef struct no
{
char data;
struct no *lchild,*rchild;
}*node;
void create(node &sa,string in,string post)
{
if(in.length()==0)
return;
sa=new no();
sa->data=post[post.length()-1];//根节点
sa->lchild=sa->rchild=NULL;
string inl,inr,postl,postr;
int i=in.find(post[post.length()-1]);
inl=in.substr(0,i);
inr=in.substr(i+1,in.length());
postl=post.substr(0,inl.length());
postr=post.substr(inl.length(),inr.length());
create(sa->lchild,inl,postl);
create(sa->rchild,inr,postr);
}
void pre(node &sa)
{
if(sa!=NULL)
{
cout<<sa->data;
pre(sa->lchild);
pre(sa->rchild);
}
}
int main()
{
string inorder,postorder;
cout<<"请输入中序遍历:"<<endl;
cin>>inorder;
cout<<"请输入后序遍历:"<<endl;
cin>>postorder;
node head=new no();
create(head,inorder,postorder);
cout<<"前序遍历结果:"<<endl;
pre(head);
cout<<endl;
return 0;
}
该博客介绍了如何根据二叉树的中序和后序遍历结果来重构前序遍历的过程。通过分析后序遍历的最后一个节点作为根节点,并在中序遍历中确定左右子树的位置,可以递归地构建整颗二叉树,从而得到前序遍历的序列。


被折叠的 条评论
为什么被折叠?



