思路:中序遍历–根结点,左子树,右子树;后序遍历–左子树,右子树,根结点。

那么在找到根结点之后就可以开始划分左右子树了。左子树的先序第一个节点是根,左子树的后序最后一个节点是根。

例如

1 2 3 4 6 7 5

2 6 7 4 5 3 1

当前的根结点就是1,在先序中得到左子树的根结点就是2,再在后序中知道左子树的节点就是{2},那么就得到左子树了,剩下的就是右子树。

如何判断重建的树是否唯一?非叶结点如果只有左子树或者右子树,那么就不唯一。

注意:如果你使用数组实现的二叉树,那么把数组开大一点,只开maxn=30+5的话第一组数据会WA(本人WA了半个小时才猜到这个套路),后来直接开10000过掉


AC代码

#include <stdio.h>
#include <string.h>
const int maxn = 10000+5;
bool isUnique;
int pre[maxn], post[maxn];
int left[maxn], right[maxn];
int ans[maxn], nodes;

//return root
int reBuild(int prel, int prer, int postl, int postr) {
    if(prel > prer) return -1;
    int root = pre[prel];
    if(prel == prer) { //leaf
        return root;
    }
    //left-tree
    int l1 = prel+1, r2;
    for(r2 = postl; r2 < postr; r2++) {
        if(post[r2] == pre[l1]) {
            break;
        }
    }
    int len = r2 - postl + 1;
    // check unique
    if(len == prer-prel) {
        isUnique = false;
    }
    int r1 = l1 + len -1;
    int l2 = postl;
    //rebulid left-tree
    left[root] = reBuild(l1, r1, l2, r2);
    //rebuild right-tree
    right[root] = reBuild(r1+1, prer, r2+1, prer-1);
    return root;
}

void getInorder(int root) {
    if(root == -1) return;
    getInorder(left[root]);
    ans[nodes++] = root;
    getInorder(right[root]);
}

int main() {
    int n;
    while(scanf("%d", &n) == 1) {
        isUnique = true;
        memset(left, -1, sizeof(left));
        memset(right, -1, sizeof(right));
        for(int i = 0; i < n; i++) {
            scanf("%d", &pre[i]);
        }
        for(int i = 0; i < n; i++) {
            scanf("%d", &post[i]);
        }
        int root = reBuild(0, n-1, 0, n-1);
        nodes = 0;
        getInorder(root);
        if(isUnique) {
            printf("Yes\n");
        } else {
            printf("No\n");
        }
        for(int i = 0; i < nodes; i++) {
            printf("%d%c", ans[i], i == nodes-1 ? '\n' : ' ');
        }
    }
    return 0;
}

如有不当之处欢迎指出!

PAT1119. Pre- and Post-order Traversals的更多相关文章

  1. Construct a tree from Inorder and Level order traversals

    Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is a ...

  2. [LeetCode] Rank Scores 分数排行

    Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ra ...

  3. HDU 4358 Boring counting(莫队+DFS序+离散化)

    Boring counting Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 98304/98304 K (Java/Others) ...

  4. ASP.NET MVC : Action过滤器(Filtering)

    http://www.cnblogs.com/QLeelulu/archive/2008/03/21/1117092.html ASP.NET MVC : Action过滤器(Filtering) 相 ...

  5. HDU 1160 FatMouse's Speed

    半个下午,总算A过去了 毕竟水题 好歹是自己独立思考,debug,然后2A过的 我为人人的dp算法 题意: 为了支持你的观点,你需要从给的数据中找出尽量多的数据,说明老鼠越重速度越慢这一论点 本着“指 ...

  6. UVA 1175 Ladies' Choice 稳定婚姻问题

    题目链接: 题目 Ladies' Choice Time Limit: 6000MS Memory Limit: Unknown 64bit IO Format: %lld & %llu 问题 ...

  7. Spring Cloud Zuul 限流详解(附源码)(转)

    在高并发的应用中,限流往往是一个绕不开的话题.本文详细探讨在Spring Cloud中如何实现限流. 在 Zuul 上实现限流是个不错的选择,只需要编写一个过滤器就可以了,关键在于如何实现限流的算法. ...

  8. [LeetCode] 系统刷题4_Binary Tree & Divide and Conquer

    参考[LeetCode] questions conlusion_InOrder, PreOrder, PostOrder traversal 可以对binary tree进行遍历. 此处说明Divi ...

  9. LeetCode: Recover Binary Search Tree 解题报告

    Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recove ...

  10. [LeetCode] questions conlusion_InOrder, PreOrder, PostOrder traversal

    Pre: node 先,                      Inorder:   node in,           Postorder:   node 最后 PreOrder Inorde ...

随机推荐

  1. linux_目录结构

    目录的作用是什么? 1. 归档和分类 2. 区分同名文件 什么是FHS? 目录层次标准,linux目录规范标准 linux系统目录有哪些特点? 1. 逻辑上所有目录都在 / 目录下,根目录是所有目录的 ...

  2. 用MapViewOfFile处理大文件-内存不足

    用MapViewOfFile处理大文件时,如果文件过大,如400M,则无法一次性映射入内存,否则会出现1132错误,即内存不足.原因可能为操作系统无法找到连续的内存.因此需要通过分页的方式,逐页将文件 ...

  3. redis五大类型用法

    Redis五大类型:字符串(String).哈希/散列/字典(Hash).列表(List).集合(Set).有序集合(sorted set)五种Controller:@Resource RedisTe ...

  4. 第一章 C++基本认识

    1.使用visual studio时让程序暂停,在return前加上这个: char response; std::cin >> response; 2.c++程序开发流程 3.变量名的命 ...

  5. 1、突然对jQuery的心血来潮

    起因 随着饿百新零售项目一期的告一段落,算是暂时从加班的修罗场里面解放出来了,于是就想搞点事情,正好看项目js库的时候发现了躺在角落的jQuery,想到当初看源码的时候断断续续的没有看完一直是心头的遗 ...

  6. MUI 页面传值,因为用的是H5+ plus方法所以要在真机上才能测试出效果

    页面a.html <!doctype html> <html> <head> <meta charset="UTF-8"> < ...

  7. SQL Server比较2table字段的差异

    由于项目前后用了2个数据库,需要统计数据库结构的变化,需要统计每个表的变化,由于人工核对挺浪费时间,就写了一点代码: 1.统计表的字段数量(查询表有多少列): select count(name)   ...

  8. Python学习笔记(一):列表和元组

    1.列表和元组的主要区别在于:列表可以修改,元组则不能.即如果要根据要求添加元素,列表更适合,    如果出于某种原因,序列不能修改的时候,使用元组更为合适. 2.通用序列操作1)索引:正数索引时,p ...

  9. Go笔记-垃圾回收集和SetFinalizer

    [垃圾回收]     1- Go的开发者也不用写代码来释放程序中不再使用的变量和结构占用内存,Go中有独立的进程,垃圾回收器(GC),处理这些事情.它会搜索不再使用的变量然后释放它们.     2- ...

  10. 洛谷 [P4016] 负载平衡问题

    贪心做法 第一眼看见觉得和均分纸牌差不多,然而因为这是环形的,并不能用均分纸牌的方法做,但是均分纸牌的思想仍然适用 首先我们假设平均数为sum1. 那么对于第1个人,我们假设他给第N个人K个糖果, 第 ...