求树的遍历

终于完全会了,我真是太菜了!竟然一直忘了一个很小的地方导致没对.....

一.中序和先序求后序

题目:P1827 美国血统 American Heritage

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<string>
#include<cstring>
#define ll long long int
using namespace std;
const int maxn=999999999;
const int minn=-999999999;
inline int read() {
	char c = getchar();
	int x = 0, f = 1;
	while(c < '0' || c > '9') {
		if(c == '-') f = -1;
		c = getchar();
	}
	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
	return x * f;
}
string zhong,qian;
void search(int l1,int r1,int l2,int r2) {
	int place=zhong.find(qian[l2]);
	if(place>l1)	search(l1,place-1,l2+1,l2+(place-l1)+1);
	if(place<r1)	search(place+1,r1,l2+(place-l1)+1,r2);
	cout<<qian[l2];
}
int main() {
	cin>>zhong>>qian;
	int len1=zhong.length();
	int len2=qian.length();
	search(0,len1-1,0,len2-1);
	return 0;
}

二.求先序

题目:P1030 求先序排列

#include<bits/stdc++.h>
using namespace std;

inline int read() {
	char c=getchar();
	int x=0,f=1;
	while(c<'0'||c>'9') {
		if(c=='-') f=-1,c=getchar();
	}
	while(c>='0'&&c<='9') {
		x=x*10+(c-'0') ,c=getchar();
	}
	return x*f;
}
string zhong,hou;
int len1,len2;
void search(int l1,int r1,int l2,int r2)
{
	int place=zhong.find(hou[r2]);
	cout<<zhong[place]; 
	if(place>l1) search(l1,place-1,l2,place-l1+l2-1);//有左子树的情况 
	if(place<r1) search(place+1,r1,place-l1+l2,r2-1);//有右子树的情况
}
int main()
{
	cin>>zhong>>hou;
	len1=zhong.length();
	len2=hou.length();
	search(0,len1-1,0,len2-1);
	return 0;
}
posted @ 2019-06-27 11:40  pyyyyyy  阅读(156)  评论(1编辑  收藏  举报