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

该博客介绍了如何根据二叉树的中序和后序遍历结果来重构前序遍历的过程。通过分析后序遍历的最后一个节点作为根节点,并在中序遍历中确定左右子树的位置,可以递归地构建整颗二叉树,从而得到前序遍历的序列。

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

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值