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\n";
    else cout << "No\n";
    inOrder(root);
    return 0;
}
posted @ 2016-11-26 00:18  demianzhang  阅读(1799)  评论(0编辑  收藏  举报