根据二叉树的中序和后序遍历,求前序遍历

先构建二叉树,后进行中序遍历

1.后序的最后一个节点是二叉树的根节点,即前序遍历的第一个节点,找到其在中序遍历中的位置,分为做字数和右子树两部分
                      A
                /           \
           CBH        DE 

2.左子树中的节点在后序遍历中位于最右边的节点是当前根节点,找到其在中序遍历中的位置,以此类推,分别找到左子树和右子树

                    A
                /        \
               B      D
   /  \     \
     C  H   E
所以前序遍历结果是:ABCHDE

#include 
#include 
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<data;
		pre(sa->lchild);
		pre(sa->rchild);
	}
}
int main()
{
	string inorder,postorder;
	cout<<"请输入中序遍历:"<>inorder;
	cout<<"请输入后序遍历:"<>postorder;
	node head=new no();
	create(head,inorder,postorder);
	cout<<"前序遍历结果:"<


你可能感兴趣的:(水题)