A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater or equal to than the node’s key.
- Both the left and right subtrees must also be binary search trees.
If we swap the left and right subtrees of every node, then the resulting tree is called the Mirror Image of a BST.
Now given a sequence of integer keys, you are supposed to tell if it is the preorder traversal sequence of a BST or the mirror image of a BST.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N integer keys are given in the next line. All the numbers in a line are separated by a space.
Output Specification:
For each test case, first print in a line YES if the sequence is the preorder traversal sequence of a BST or the mirror image of a BST, or NO if not. Then if the answer is YES, print in the next line the postorder traversal sequence of that tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.
Sample Input 1:
7
8 6 5 7 10 8 11
Sample Output 1:
YES
5 7 6 8 11 10 8
Sample Input 2:
7
8 10 11 8 6 7 5
Sample Output 2:
YES
11 8 10 7 5 6 8
Sample Input 3:
7
8 6 8 5 10 9 11
Sample Output 3:
NO
思路:
1、二叉搜索树先序转后序,见下图
2、设置标记变量isMirror标记是否为二叉搜索树的镜像,设isMirror初始为false,如果中序遍历序列中元素个数不等于n(即中序遍历序列不存在),置isMirror为true,中序序列清空,重新做一次步骤1;如果中序遍历序列中元素个数仍然不等于n(即中序遍历序列不存在),输出NO,否则输出YES以及中序序列。
特别注意:
左子树需要从root+1开始遍历,要去掉root,又称去根操作!!!
代码如下
#include<iostream>
#include<vector>
using namespace std;
vector<int> pre,post;
bool isMirror = false;
void postOrder(int root,int end)
{
if(root > end) return;
int i = root+1,j = end;
if(!isMirror){
while(i <= end && pre[i] < pre[root]) i++;
while(j > root && pre[j] >= pre[root]) j--;
}else{
while(i <= end && pre[i] >= pre[root]) i++;
while(j > root && pre[j] < pre[root]) j--;
}
postOrder(root+1, j);
postOrder(i, end);
post.push_back(pre[root]);
}
int main()
{
int n;
cin>>n;
pre.resize(n);
for(int i = 0; i < n; i++){
scanf("%d", &pre[i]);
}
postOrder(0, n-1);
if(post.size() != n){
isMirror = true;
post.clear();
postOrder(0, n-1);
}
if(post.size() == n){
cout<<"YES"<<endl;
for(int i = 0; i < post.size()-1; i++){
cout<<post[i]<<" ";
}
cout<<post[post.size()-1];
}else{
cout<<"NO"<<endl;
}
return 0;
}
来源:CSDN
作者:波点兔
链接:https://blog.csdn.net/qq_42437577/article/details/104108437