1119 Pre- and Post-order Traversals

1119 Pre- and Post-order Traversals (30分)

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder 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

思路:

注意的是通过在后序遍历中的 post[postR - 1] 得到在先序遍历中右子树的根结点 i,然后通过该结点判断 i - preL - 1 (左子树结点个数)是否 <= 1 如果 是 说明能够构建的树不唯一

否则继续遍历,要注意的是边界判断条件,普通的 先序 中序遍历推出 后序遍历 或者 后序遍历, 中序遍历 推出先序遍历 传统方法得到的i(中序遍历中根结点的位置) 是不能取到的 因此
可以直接通过判断 L > r 返回, 但是此题中 i可以取到,就需要加上返回条件 l == r, l > r的条件也需要加上(因为在遍历左子树时 和传统方法一样 preL, i - 1)

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxsize = 35;
int pre[maxsize], post[maxsize], in[maxsize], cnt = 0;
bool isUnique = true;
void inOrder(int preL, int preR, int postL, int postR) {
    if(preL > preR) return; //当左子树没有结点就会陷入死循环
    if(preL == preR) { //这步实现的原因是 i 表示的是右根结点能取到, 而 i 和 preR 这个值会一直不变
        in[cnt++] = pre[preL];
        return;
    }
    int i = preL;
    while(pre[i] != post[postR - 1]) i++;
    if(i - preL <= 1) {
        isUnique = false;
    }
    inOrder(preL + 1, i - 1, postL, postL + (i - preL - 1) - 1);
    in[cnt++] = pre[preL];
    inOrder(i, preR, postL + (i - preL - 1), postR - 1);

}
int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
        scanf("%d", &pre[i]);
    }
    for(int i = 0; i < n; i++) {
        scanf("%d", &post[i]);
    }
    inOrder(0, n - 1, 0, n - 1);
    printf("%s\n", isUnique == true ? "Yes" : "No");
    for(int i = 0; i < cnt; i++) {
        printf("%s%d", i == 0 ? "" : " ", in[i]);
    }
    puts("");
    return 0;
}

posted @ 2020-03-06 21:54  yxdh  阅读(123)  评论(0编辑  收藏  举报