uva 10701(简单二叉树)

该问题要求根据给定的二叉树中序和前序遍历,计算出后序遍历的结果。题目提供了示例输入和输出,并指出每个测试用例包含树的节点数以及两个字符串,分别表示前序和中序遍历的顺序。

Problem F - Pre, in and post

Time Limit: 1 second

A common problem in data structures is to determine the traversal of a binary tree. There are three classic ways to do it:

Pre-order: You must visit in sequence the root, left subtree and the right subtree.
In-order: You must visit in sequence the left subtree, the root and the right subtree.
Post-order: You must visit in sequence the left subtree, the right subtree and the root.

See the picture below:

graph.png

The pre, in and post-order traversal are, respectively,  ABCDEF, CBAEDF and CBEFDA. In this problem, you must compute the post-order traversal of a binary tree given its in-order and pre-order traversals.

Input

The input set consists of a positive number C ≤ 2000, that gives the number of test cases and C lines, one for each test case. Each test case starts with a number 1 ≤ N ≤ 52, the number of nodes in this binary tree. After, there will be two strings S1 and S2 that describe the pre-order and in-order traversal of the tree. The nodes of the tree are labeled with different characters in the range a..z and A..Z. The values of N, S1 and S2 are separeted by a blank space.

Output

For each input set, you should output a line containing the post-order transversal for the current tree.

Sample input

3
3 xYz Yxz
3 abc cba
6 ABCDEF CBAEDF

Sample output

Yzx
cba
CBEFDA

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;

const int maxn = 60;
struct Node{
	char c;
	int son[2];
}node[maxn];
int N , cnt;
string s1 , s2;

void initial(){
	for(int i = 0;i < maxn;i++){
		node[i].c = '0';
		node[i].son[0] = -1;
		node[i].son[1] = -1;
	}
	s1.clear();
	s2.clear();
	cnt = 0;
}

void readcase(){
	cin >> N >> s1 >> s2;
}

int get_tree(string str2){
	if(s1.length() > 0){
		int n = cnt++;
		node[n].c = s1[0];
		s1 = s1.substr(1 , s1.length()-1);
		for(int i = 0;i < str2.length();i++){
			if(node[n].c == str2[i]){
				if(i > 0){
					node[n].son[0] = get_tree(str2.substr(0 , i));
				}
				if(str2.length()-i-1 > 0){
					node[n].son[1] = get_tree(str2.substr(i+1 , str2.length()-i-1));
				}
				return n;
			}
		}
		return -1;
	}
}

void print(int i){
	if(node[i].son[0] != -1){
		print(node[i].son[0]);
	}
	if(node[i].son[1] != -1){
		print(node[i].son[1]);
	}
	printf("%c" , node[i].c);
}

void computing(){
	int head = get_tree(s2);
	print(0);
	printf("\n");
}

int main(){
	int C;
	cin >> C;
	while(C--){
		initial();
		readcase();
		computing();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值