PAT (Advanced Level) Practise 1119 Pre- and Post-order Traversals (30)

来源:互联网 发布:centos与linux区别 编辑:程序博客网 时间:2024/06/05 16:33

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

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Special
作者
CHEN, Yue

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:
71 2 3 4 6 7 52 6 7 4 5 3 1
Sample Output 1:
Yes2 1 6 4 7 3 5
Sample Input 2:
41 2 3 42 4 3 1
Sample Output 2:
No2 1 3 4

题意:给出一棵树的前序遍历和后序遍历,问这棵树是否唯一,并输出中序遍历

解题思路:树是否唯一其实就是看除了叶子以外的每个节点是否都有两个儿子, 因为有一个儿子的话,它既可以是左儿子也可以是右儿子,这也就是前序和中序不能确定一棵唯一二叉树的原因


#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <queue>#include <stack>#include <cmath>#include <map>#include <bitset>#include <set>#include <vector>#include <functional>using namespace std;#define LL long longconst int INF = 0x3f3f3f3f;int n, a[35], b[35], c[35], d[35],x[35][2],flag;int dfs(int l, int r, int ll, int rr){if (l > r || ll > rr) return 0;if (l == r) return l;int cnt = 0, i = l + 1, j = ll, k;while (1){c[cnt] = a[i++];d[cnt++] = b[j++];sort(c, c + cnt);sort(d, d + cnt);for (k = 0; k < cnt; k++)if (c[k] != d[k]) break;if (k >= cnt) break;}x[l][0] = dfs(l + 1, i - 1, ll, j - 1);x[l][1] = dfs(i, r,j,rr);return l;}void dfs1(int k){if (x[k][0]) dfs1(x[k][0]);if (flag) printf("%d", a[k]);else printf(" %d", a[k]);flag = 0;if (x[k][1]) dfs1(x[k][1]);}int main(){while (~scanf("%d", &n)){for (int i = 1; i <= n; i++) scanf("%d", &a[i]);for (int i = 1; i <= n; i++) scanf("%d", &b[i]);memset(x, 0, sizeof x);dfs(1, n, 1, n);flag = 1;for (int i = 1; i <= n; i++)if ((x[i][0] && !x[i][1]) || (!x[i][0] && x[i][1])) flag = 0;if (flag) printf("Yes\n");else printf("No\n");flag = 1;dfs1(1);printf("\n");}return 0;}

阅读全文
0 0
原创粉丝点击