求先序遍历、后序遍历

根据定理来说不需要建树,直接可输出

求先序遍历 洛谷P1030
题目描述

给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度\le 8≤8)。

sample input
BADC
BDCA
sample output
ABCD
代码片
#include<bits/stdc++.h>
using namespace std;

string s1,s2;//s2记录中序遍历,s1记录先序遍历
int n;

void build(int x, int s, int e) {
	for(int i=s; i<=e; i++ ) {
		if ( s1[x]==s2[i] ) {
			cout<<s1[x];
			build(x-e+i-1,s,i-1);//注意计算一下根节点的位置就好了
			build(x-1,i+1,e);
			return;
		}
	}
}

int main() {
	cin>>s2>>s1;
	n=s1.length();
	build(n-1,0,n-1);
	return 0;
} 
求后序遍历 洛谷P1827 美国血统 American Heritage
代码片
#include<bits/stdc++.h>
using namespace std;

string s1,s2;//s1为中序遍历,s2为后序遍历
char tree[1000];
int cnt;

void build_tree(int x, int s, int e) {
	for(int i=s; i<=e; i++ ) {
		if ( s2[x]==s1[i] ) {
			build_tree(x+1,s,i-1);
			build_tree(x+i-s+1,i+1,e);//i-s为左子树根的数目 
			cout<<s1[i];
			return;
		}
	}
}

int main() {
	cin>>s1>>s2;
	int cnt=s1.length();
	build_tree(0,0,s1.length()-1);
	return 0;
}

碰到这一类题,已知前序遍历和后序遍历,求中序遍历有几种

洛谷P1229 遍历问题
思路

只有一个儿子结点的情况下才可能出现两种中序遍历。
根据前序遍历和后序遍历的特点,可发现规律
eg. 前序遍历abc和后序遍历cbaAlt
若这个结点有且只有一个儿子,那么它就有两种情况,最后就是2^n种

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

int main() {
	string s1,s2;
	int ans=0;
	cin>>s1>>s2;
	for(int i=0; i<s1.length()-1; i++) {
		for(int j=1; j<s2.length(); j++) {
			if ( s1[i]==s2[j] && s1[i+1]==s2[j-1] ) ans++;
		}
	}
	printf("%d\n",1<<ans);
	return 0;
}
发布了13 篇原创文章 · 获赞 6 · 访问量 579

猜你喜欢

转载自blog.csdn.net/zx1020354953/article/details/104130761