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;
}

转载于:https://www.cnblogs.com/demian/p/6103285.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值