PAT A1119 Pre- and Post-order Traversals ——小楼一夜听春雨,深巷明朝卖杏花

PAT A1119 Pre- and Post-order Traversals

  • 到此为止终于把甲级上的这155道都摸了一遍,前后花了好长好长时间——我也不想这么慢,同样过这一生,比别人少做好多事。。。
  • 先序是根左右,后序是左右根,所以当一个节点只有左子树或只有右子树的时候,两人都不清楚到底是左子树还是右子树——so不能唯一确定
  • 本题的想法是走跟之前正常建树一样的流程:一个序列提供根节点,另一个序列定位,然后划分左右子树。不同的是这里要提供的根节点是当前序列【左子树的根节点】(if没有左子树,那个位置就是右子树的根节点,反正没法分辨,所以假设是左子树即可),而之前用中序建树是提供当前序列的根节点
  • 在这里特别注意,build右子树时传入的参照同样应该是这个右子树的【左子树的根节点】,即先序中右子树根节点的下一个位置,不注意容易习惯性传右子树根节点
  • 在只做了上面传参改动的情况下会发现当递归到序列只有一个节点的时候,由于int pos = postL; pos以postL为下界,那么往下build左子树时这个为1的长度就会一直被保留,无法结束。所以在前面加了个if滤掉这种情况。之后看到更优美的方法再改
  • 如上所述,判断是否唯一就看有没有节点只有单个子树。我这里由于优先build左子树,所以实际上只可能存在(postorder[postR].right == -1 && postorder[postR].left != -1)的情况
  • 最后一行换行,否则格式错误。。。
  • 在这里插入图片描述
#include<iostream>
#include<vector>

using namespace std;

struct Node{
    int data,left,right;
};
vector<Node> postorder;
vector<int> preorder;
int N,cnt = 0;

bool flag = true;
int build(int root,int postL,int postR){
    if(postL > postR) return -1;
    if(postL == postR){
        postorder[postR].left = -1;
        postorder[postR].right = -1;
        return postR;
    }
    int pos = postL;
    while(postorder[pos].data != preorder[root]) pos ++;
    postorder[postR].left = build(root + 1,postL,pos);
    postorder[postR].right = build(root + 1 + pos - postL + 1,pos + 1,postR - 1);
    if((postorder[postR].left == -1 && postorder[postR].right != -1)
       || (postorder[postR].right == -1 && postorder[postR].left != -1)) flag = false;
    return postR;
}

void inorder(int root){
    if(postorder[root].left != -1) inorder(postorder[root].left);
    cout << postorder[root].data;
    cnt ++;
    if(cnt != N) cout << ' ';
    else cout << '\n';
    if(postorder[root].right != -1) inorder(postorder[root].right);
}

int main(){

    cin >> N;
    preorder.resize(N);
    postorder.resize(N);
    for(int i = 0;i < N;i ++) cin >> preorder[i];
    for(int i = 0;i < N;i ++) cin >> postorder[i].data;
    int root = build(1,0,N - 1);
    if(flag) cout << "Yes\n";
    else cout << "No\n";
    inorder(root);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值