PAT 甲级 刷题日记|A 1119 Pre- and Post-order Traversals (30 分)

题目

traversal sequences, or preorder and inorder traversal sequences. However, if only the postorder and preorder traversal sequences are given, the corresponding tree may no longer be unique.

Now given a pair of postorder and preorder traversal sequences, you are supposed to output the corresponding inorder traversal sequence of the tree. If the tree is not unique, simply output any one of them.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 30), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first printf in a line Yes if the tree is unique, or No if not. Then print in the next line the inorder traversal sequence of the corresponding binary tree. If the solution is not unique, any answer would do. It is guaranteed that at least one solution exists. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input 1:

7
1 2 3 4 6 7 5
2 6 7 4 5 3 1结尾无空行

Sample Output 1:

Yes
2 1 6 4 7 3 5结尾无空行

Sample Input 2:

4
1 2 3 4
2 4 3 1
结尾无空行

Sample Output 2:

No
2 1 3 4
结尾无空行

思路

给定前序+后序序列,求对应的树的中序序列,并判断树是否唯一

什么情况唯一:树的每个节点 要么左右子节点都没有,要么都有时唯一。

不唯一:树的某个节点 只有一个子节点,此时无论是左节点还是右节点。其对应的前序序列和后序序列都是一样的。

如何根据前序+后序求树呢?

先序序列的第一个节点a是根节点,第二个节点b是根节点a的子节点。如果后序序列的倒数第二个节点c等于正序的第二个节点b,说明该根节点a只有一个子节点,对应的树不唯一;自己设置默认的即可。

如果c和b不相等,则说明a节点有左右两棵子树,b和c就是a的左右子节点。然后划分左右子树继续递归即可。

输出要带回车,否则会格式错误。

代码

#include 
using namespace std;

const int maxn = 33;
int flag = 0;
int pre[maxn];
int post[maxn];
vector res;

struct node{
    int i;
    node* leftchild;
    node* rightchild;
    node(int data): i(data), leftchild(NULL), rightchild(NULL){
    }
};

node* create(int prea, int preb, int posta, int postb) {
    if (prea > preb) return NULL;
    if (prea == preb) return new node(pre[prea]);
    int ro = pre[prea];
    node* root = new node(ro);
    int son = pre[prea + 1];
    int i;
    for (i = posta; i <= postb; i++) {
        if (post[i] == son) break;
    }
    int numleft = i - posta + 1;
    if (i == postb - 1) flag = 1;
    root->leftchild = create(prea + 1, prea + numleft, posta, posta + numleft - 1);
    root->rightchild = create(prea + 1 + numleft, preb, posta + numleft, postb - 1);
    return root;
}

void inorder(node* root) {
    if (root == NULL) return;
    inorder(root->leftchild);
    res.push_back(root->i);
    inorder(root->rightchild);
}

int main() {
    int len;
    cin>>len;
    for (int i = 1; i <= len; i++) {
        cin>>pre[i];
    }
    for (int i = 1; i <= len; i++) {
        cin>>post[i];
    }
    
    node* root = create(1, len, 1, len);
    if (flag) cout<<"No"<

你可能感兴趣的:(PAT 甲级 刷题日记|A 1119 Pre- and Post-order Traversals (30 分))