| A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
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 |
- 7
- 8 6 5 7 10 8 11
- YES
- 5 7 6 8 11 10 8
- 7
- 8 10 11 8 6 7 5
- YES
- 11 8 10 7 5 6 8
- 7
- 8 6 8 5 10 9 11
NO
题目大意
给你一串数组,判断这是否是对⼀棵⼆叉搜索树或其镜像翻转后,进⾏前序遍历的结果是的话输出 YES + 该树的后续遍历否则 NO
思路
分类讨论是否为镜像翻转
- #include
- using namespace std;
- vector<int> tree1,tree2;
- int N,num;
- bool flag = true; // 判断有无镜像翻转
- void create(int head,int tail);
- int main()
- {
- cin >> N;
- for(int z=0;z
- cin >> num;
- tree1.push_back(num);
- }
- create(0,N-1);
- if(tree2.size()!=tree1.size()){
- tree2.clear();
- flag = false;
- create(0,N-1);
- }
-
- if(tree2.size()!=tree1.size()) puts("NO");
- else
- {
- cout << "YES" << endl << tree2[0];
- for(int z=1;z
" " << tree2[z]; - }
- return 0;
- }
- void create(int head,int tail)
- {
- if(head>tail) return;
- int left=head+1,right=tail;
- if(flag){
- while (left<=tail && tree1[head]>tree1[left]) left++;
- while (right>head && tree1[head]<=tree1[right]) right--;
- }else{
- while (left<=tail && tree1[head]<=tree1[left]) left++;
- while (right>head && tree1[head]>tree1[right]) right--;
- }
- if(left-right>1) return;
- create(head+1,left-1);
- create(right+1,tail);
- tree2.push_back(tree1[head]);
- }