[ACM]【二叉树】遍历问题

线段切割

注:持续更新

已知先序中序求后序

洛谷1827 美国血统

代码:

#include<bits/stdc++.h>
using namespace std;
void dfs(string xx,string zx){
	if(!xx.size()) return;
	int pos=zx.find(xx[0]);
	dfs(xx.substr(1,pos),zx.substr(0,pos));
	dfs(xx.substr(pos+1),zx.substr(pos+1));
	printf("%c",xx[0]);
}
int main(){
	string xx,zx;
	cin>>zx>>xx;
	dfs(xx,zx);
	printf("\n");
}

已知后序中序求前序

洛谷1030 求先序排列

代码:

#include<bits/stdc++.h>
using namespace std;
void dfs(string zx,string hx){
	if(!zx.size())return;
	int pos=zx.find(hx[hx.size()-1]);
	printf("%c",zx[pos]);
	dfs(zx.substr(0,pos),hx.substr(0,pos));
	dfs(zx.substr(pos+1),hx.substr(pos,hx.size()-pos-1));
} 
int main(){
	string zx,hx;
	cin>>zx>>hx;
	dfs(zx,hx);
	printf("\n");
}

已知先序后序求中序数目

洛谷1229 遍历问题

代码:

思路:显然,如果只有一个儿子的话就会产生一次中序的分歧。找只有一个儿子的节点数,只用找有多少对字母在前序和后序中刚好紧挨着并相互调换即可。比如在前序中为ab,后序中为ba,显然,a只有一个儿子b。

#include<bits/stdc++.h>
using namespace std;
int main(){
	char a[400],b[400];
	scanf("%s%s",a,b);
	long long n=0;
	for(int i=0;i<strlen(a)-1;i++)
		for(int j=1;j<strlen(b);j++)
			if(b[j]==a[i]&&a[i+1]==b[j-1]){
				n++;continue;
			}
	printf("%lld\n",1<<n);
}
发布了9 篇原创文章 · 获赞 0 · 访问量 99

猜你喜欢

转载自blog.csdn.net/weixin_45497996/article/details/105450279