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