_what

博客园 首页 新随笔 联系 订阅 管理

题意:已知二叉树前序和中序遍历,求后序遍历
Solution:
要求解post-order(str1, str2)的话,首先不难发现,根据‘前序遍历’str1=‘根节点’+‘左子树的前序遍历’+‘右子树的前序遍历’,我可以知道这棵二叉树的根节点root便是str1的第一个字符
在知道了‘根节点’root之后,我便可以利用‘中序遍历’str2=‘左子树的中序遍历’+‘根节点’+‘右子树的中序遍历’,求解出‘左子树的中序遍历’str2L和‘右子树的中序遍历’str2R

/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

typedef long long LL;
typedef unsigned long long ULL;
using namespace std;

bool Sqrt(LL n) { return (LL)sqrt(n) * sqrt(n) == n; }
const double PI = acos(-1.0), ESP = 1e-10;
const LL INF = 99999999999999;
const int inf = 999999999, N = 26 + 2;
char pre[N], in[N];

void Run(char * pre, char * in, int len)
{
	if(len < 1) return;	//不要忘记终止条件
	int i = 0;
	while(in[i] != pre[0]) i++;    //找根节点
	Run(pre + 1, in, i);
	Run(pre + i + 1, in + i + 1, len - i - 1);
	printf("%c", pre[0]);
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	scanf("%s%s", pre, in);
	int n = strlen(pre);
	Run(pre, in, n);

	return 0;
}
/*
    input:
    output:
    modeling:
    methods:
    complexity:
    summary:
*/
posted on 2019-10-11 09:26  _what  阅读(133)  评论(0编辑  收藏  举报