luogu1030 求先序序列(NOIP2001普及组第3题)

版权声明:本文为博主原创文章,未经博主允许不得转载,不得用于商业用途。 https://blog.csdn.net/WDAJSNHC/article/details/82346276

luogu1030 求先序序列(NOIP2001普及组第3题)

时空限制    1000ms/128MB

题目描述

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

输入输出格式

输入格式:

2行,均为大写字母组成的字符串,表示一棵二叉树的中序与后序排列。

输出格式:

1行,表示一棵二叉树的先序。

输入输出样例

输入样例#1:

BADC
BDCA

输出样例#1:

ABCD

代码

#include<iostream>
#include<string>
using namespace std;
struct node{
	char data;
	node *lch,*rch;
};

void create(node *&root,string s1,string s2){
	if (s1=="") { root=NULL; return; }
	root = new node;
	int len=s1.size();
	root->data = s2[len-1];
	int pos=s1.find(s2[len-1]);
	create(root->lch,s1.substr(0,pos),s2.substr(0,pos));
	create(root->rch,s1.substr(pos+1,len-pos-1),s2.substr(pos,len-pos-1));
}

void firstord(node *root){
	if (root){
		cout<<root->data;
		firstord(root->lch);
		firstord(root->rch);
	}
}

int main(){
	string s1,s2;
	cin>>s1>>s2;
	node *root(NULL);
	create(root,s1,s2);
	firstord(root);
	cout<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/WDAJSNHC/article/details/82346276