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

[各种面试题] 前后序遍历统计树

2018年04月12日 ⁄ 综合 ⁄ 共 732字 ⁄ 字号 评论关闭

对于包含n个结点的二叉树(树中结点编号从1到n),已知前序和后序遍历序列,我们知道不一定能唯一的恢复这棵树。请计算出满足条件的二叉树的总数。

样例:

前序遍历序列preorder:1 2
后序遍历序列postorder:2 1

一共有2棵满足条件的二叉树:
    1       1
   /         \
  2           2

确定范围的时候好烦啊。

int _count(vector<int>& pre,int preL,int preR,vector<int>& post,int postL,int postR);
int countValidTrees(vector<int>& preorder, vector<int>& postorder) {
	if ( preorder.size()!=postorder.size() )
		return 0;
	return _count(preorder,0,preorder.size()-1,postorder,0,postorder.size()-1);
}
int _count(vector<int>& pre,int preL,int preR,vector<int>& post,int postL,int postR)
{
	if ( preL > preR )
		return 1;
	if ( pre[preL] != post[postR] )
		return 0;
	if ( preL==preR )
		return 1;
	int cnt=0;
	int k=preR-preL;
	for(int left=0;left<=k;left++)
	{
		cnt+=_count(pre,preL+1,preL+left,post,postL,postL+left-1)
			* _count(pre,preL+left+1,preR,post,postL+left,postR-1);
	}
	return cnt;
}

抱歉!评论已关闭.