HihoCoder - 1049

版权声明:仅供研究,转载请注明出处。 https://blog.csdn.net/CSUstudent007/article/details/82502572

 题解:

如果我要求解post-order(str1, str2)的话,首先不难发现,根据‘前序遍历’str1=‘根节点’+‘左子树的前序遍历’+‘右子树的前序遍历’,我可以知道这棵二叉树的根节点root便是str1的第一个字符!”小Ho道。

而我在知道了‘根节点’root之后,我便可以利用‘中序遍历’str2=‘左子树的中序遍历’+‘根节点’+‘右子树的中序遍历’,求解出‘左子树的中序遍历’str2L和‘右子树的中序遍历’str2R!

接下来,由于一棵子树的前序遍历和中序遍历的长度相同,那么仍然是根据‘前序遍历’str1=‘根节点’+‘左子树的前序遍历’+‘右子树的前序遍历’,我可以知道从str1的第2个字符开始的str2L.length()个字符便是‘左子树的前序遍历’str1L,而这之后的部分便是‘右子树的前序遍

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio> 
using namespace std;
const int maxn = 26;
char pre[maxn],in[maxn],pos[maxn];
void post_order(int prel,int inl,int posl,int n){
	if(n==0) return ;
	if(n==1){
		pos[posl]=pre[prel];
		return;
	}
	int i,root = pre[prel];
	pos[posl+n-1] = root;
	for(i=0;i<n;i++){
		if(in[inl+i]==root){
			break;
		}
	}
	post_order(prel+1,inl,posl,i);
	post_order(prel+i+1,inl+i+1,posl+i,n-i-1);
}
int main(){
	scanf("%s",pre);
	scanf("%s",in);
	post_order(0,0,0,strlen(pre));
	printf("%s\n",pos);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/CSUstudent007/article/details/82502572