• PAT A 1119. Pre- and Post-order Traversals (30)【二叉树遍历】


    No.1119

    题目:由前序后序二叉树序列,推中序,判断是否唯一后输出一组中序序列

    思路:前序从前向后找,后序从后向前找,观察正反样例可知,前后序树不唯一在于单一子树是否为左右子树。

             判断特征:通过查找后序序列中最后一个结点的前一个在先序中的位置,来确定是否可以划分左右孩子,如果不能,  就将其划分为右孩子(或左孩子),递归建树。

             中序遍历输出。

    #include <iostream>
    using namespace std;
    const int maxn = 31;
    
    int n, index = 0;
    int pre[maxn], post[maxn];
    bool flag = true;
    
    struct Node {
        int data;
        Node *lchild, *rchild;
    } *root;
    
    Node *create(int preL, int preR, int postL, int postR) 
    {
        if (preL > preR) return NULL;
        Node *node = new Node;
        node->data = pre[preL];
        node->lchild = NULL;
        node->rchild = NULL;
        if (preL == preR)
            return node;
        int k = 0;
        for (k = preL + 1; k <= preR; k++) 
        {
            if (pre[k] == post[postR - 1]) break;
        }
        if (k - preL > 1) 
        {
            node->lchild = create(preL + 1, k - 1, postL, postL + k - preL - 2);
            node->rchild = create(k, preR, postL + k - preL - 1, postR - 1);
        }
        else 
        {
            flag = false;
            node->rchild = create(k, preR, postL + k - preL - 1, postR - 1);
        }
        return node;
    }
    
    void inOrder(Node *node) 
    {
        if (node == NULL) return;
        inOrder(node->lchild);
        if (index < n - 1)
            cout << node->data << " ";
        else cout << node->data << endl;
        index++;
        inOrder(node->rchild);
    }
    
    int main() 
    {
        cin >> n;
        for (int i = 0; i < n; ++i) cin >> pre[i];
        for (int i = 0; i < n; ++i) cin >> post[i];
        root = create(0, n - 1, 0, n - 1);
        if (flag) cout << "Yes
    ";
        else cout << "No
    ";
        inOrder(root);
        return 0;
    }
  • 相关阅读:
    linux命令行挂载NTFS文件系统的移动硬盘
    windows 修改鼠标滚轮自然滚动
    spark sql 的metastore 对接 postgresql
    ubuntu 14.04 源码编译postgresql
    spark sql 对接 HDFS
    部署spark 1.3.1 standalong模式
    perl 打开二进制文件,并拷贝内容
    ubuntu 14 安装XML::Simple 模块
    linux 搭建unixODBC ,并对接 PostgreSQL 9.3.4
    sed 删除指定行
  • 原文地址:https://www.cnblogs.com/demian/p/6103285.html
Copyright © 2020-2023  润新知