首页 > 其他 > 详细

Hihocoder 1049

时间:2019-10-11 10:06:20      阅读:66      评论:0      收藏:0      [点我收藏+]

题意:已知二叉树前序和中序遍历,求后序遍历
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:
*/

Hihocoder 1049

原文:https://www.cnblogs.com/000what/p/11652036.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!