PAT甲级——A1119 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
#include <iostream>
#include <vector>
using namespace std;
int n, a;
vector<int>preOrder, postOrder, inOrder;
bool flag = true;//表示树的形态不唯一
void getInOrder(int root, int left, int right)
{
if (left >= right)
{
if (left == right)//只有一个节点
inOrder.push_back(preOrder[root]);
return;
}
int i = left;
while (i < right && preOrder[root + ] != postOrder[i])//查找前序遍历中下一个节点在后序中的位置
++i;
if (i == right - )//先根序列中根节点的下一结点在后根序列中的位置正好等于right-1
flag = false;
getInOrder(root + , left, i);
inOrder.push_back(preOrder[root]);
getInOrder(root + i - left + , i + , right - );
}
int main()
{
cin >> n;
for (int i = ; i < n; ++i)
{
cin >> a;
preOrder.push_back(a);
}
for (int i = ; i < n; ++i)
{
cin >> a;
postOrder.push_back(a);
}
getInOrder(, , n - );
cout << (flag ? "Yes" : "No") << endl;
for (int i = ; i < n; ++i)
cout << (i > ? " " : "") << inOrder[i];
cout << endl;
return ;
}
最新文章
- T1加权像(T1 weighted image,T1WI)
- 根据Unicode编码用C#语言把它转换成汉字的代码
- 4.4 spring-自定义标签的解析
- h5拖放-ff的bug
- centos账户管理命令(root权限)
- qt模型学习
- 《转》如何成为一个牛逼的C/C++程序员?
- 【canvas学习笔记一】基本认识
- Spring设计模式_工厂模式
- subing用法
- Java垃圾回收机制和注解
- 利用R与SAS进行关联规则挖掘
- C++自动类型转化--特殊构造函数方法和重载的运算符方法
- php解析Excel表格并且导入MySQL数据库
- leetcode560
- Mac配置Eclipse CDT的Debug出现的问题(转)
- iOS 在viewDidLayoutSubviews自动布局crash问题
- QT5 样式随笔
- [转载]在VirtualBox中收缩虚拟磁盘映像文件
- Activity的onPause()、onStop()和onDestroy()里要做的事情