算法训练 求先序排列

问题描述

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

输入格式

  两行,每行一个字符串,分别表示中序和后序排列

输出格式

  一个字符串,表示所求先序排列

  样例输入
  BADC
  BDCA

样例输出

ABCD

代码如下:

#include<iostream>
#include<string>
using namespace std;
void CoutTree(string z, string h, int len)
{
	if (len == 0)return;

	cout << h[len - 1];

	int i = 0;
	while (z[i] != h[len - 1]) { i++; }

	CoutTree(z.substr(0, i), h.substr(0, i), i);
	CoutTree(z.substr(i + 1, len - 1 - i), h.substr(i, len - 1 - i), len - 1 - i);
}
int main()
{
	string a, b;
	cin >> a >> b;

	int len = a.length();

	CoutTree(a, b, len);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/TOBEALISTENNER/article/details/81483384