现在的位置: 首页 > 综合 > 正文

已知二叉树的前序/后序遍历和中序遍历,求后序/前序遍历

2013年10月04日 ⁄ 综合 ⁄ 共 1540字 ⁄ 字号 评论关闭

首先,我们看看前序、中序、后序遍历的特性: 
前序遍历: 
    1.访问根节点 
    2.前序遍历左子树 
    3.前序遍历右子树 
中序遍历: 
    1.中序遍历左子树 
    2.访问根节点 
    3.中序遍历右子树 
后序遍历: 
    1.后序遍历左子树 
    2.后序遍历右子树 
    3.访问根节点 

好了,先说说用前序遍历和中序遍历求后序遍历 
假设前序遍历为 adbgcefh, 中序遍历为 dgbaechf 
前序遍历是先访问根节点,然后再访问子树的,而中序遍历则先访问左子树再访问根节点 
那么把前序的 a 取出来,然后查找 a 在中序遍历中的位置就得到 dgb a echf 
那么我们就知道 dgb 是左子树 echf 是右子树,因为数量要吻合 
所以前序中相应的 dbg 是左子树 cefh 是右子树 

然后就变成了一个递归的过程,具体代码如下: 

#include <iostream>
#include <string>

using namespace std;

int find(const string &str,char c)
{
	for(int i=0;i < str.size();i++)
	{
		if (c==str[i])
		{
			return i;
		}
	}
	return -1;
}

bool PreMidForPost(const string &pre, const string &mid)
{
	if (pre.size()==0)
		return false;
	if(pre.size() == 1)
	{
		cout<<pre;
		return true;
	}

	int k = find (mid,pre[0]);
	string preSub = pre.substr(1,k);
	string midSub = mid.substr(0,k);
	PreMidForPost(preSub,midSub);

	preSub = pre.substr(k+1,pre.size()-k-1);
	midSub = mid.substr(k+1,midSub.size()-k-1);
	PreMidForPost(preSub,midSub);

	cout<<pre[0];
}

int main()
{
	string pre,mid;
	while(cin>> pre >>mid)
	{
		PreMidForPost(pre,mid);
		cout<<endl;
	}
}

而已知后序遍历和中序遍历求前序遍历的过程差不多,但由于后序遍历是最后才访问根节点的 
所以要从后开始搜索,例如上面的例子,后序遍历为 gbdehfca,中序遍历为 dgbaechf 
后序遍历中的最后一个元素是根节点,a,然后查找中序中a的位置 
把中序遍历分成 dgb a echf,而因为节点个数要对应 
后序遍历分为 gbd ehfc a,gbd为左子树,ehfc为右子树,这样又可以递归计算了 
具体代码如下:
bool PostMidForPre(const string &post, const string &mid)
{
	if (post.size()==0)
	{
		return false;
	}
	if (post.size()==1)
	{
		cout<<post;
		return true;
	}
	int k = find(mid,post[post.size()-1]);

	cout<<post[post.size()-1];

	string postSub = post.substr(0,k);
	string midSub  =  mid.substr(0,k);
	PostMidForPre(postSub,midSub);
	
	postSub = post.substr(k,post.size()-k-1);
	midSub = mid.substr(k+1,midSub.size()-k-1);
	PostMidForPre(postSub,midSub);

}

 不过,最难的已知先序和后序,求中序。。。。

阿里巴巴笔试题:

抱歉!评论已关闭.