L2-004. 这是二叉搜索树吗?

参考博客

 

 1 #include <cstdio>
 2 #include <vector>
 3 using namespace std;
 4 bool isMirror;
 5 vector<int> pre;
 6 vector<int> post;
 7 void getpost(int root, int tail) {
 8     if(root > tail) return ;
 9     int i = root + 1, j = tail;
10     if(!isMirror) {
11         while(i <= tail && pre[root] > pre[i]) i++;
12         while(j > root && pre[root] <= pre[j]) j--;
13     } else {
14         while(i <= tail && pre[root] <= pre[i]) i++;
15         while(j > root && pre[root] > pre[j]) j--;
16     }
17     if(i - j != 1) return ;
18     getpost(root + 1, j);///
19     getpost(i, tail);///
20     post.push_back(pre[root]);
21 }
22 int main() {
23     int n;
24     scanf("%d", &n);
25     pre.resize(n);
26     for(int i = 0; i < n; i++)
27         scanf("%d", &pre[i]);
28     getpost(0, n - 1);
29     if(post.size() != n) {
30         isMirror = true;
31         post.clear();
32         getpost(0, n - 1);
33     }
34     if(post.size() == n) {
35         printf("YES\n%d", post[0]);
36         for(int i = 1; i < n; i++)
37             printf(" %d", post[i]);
38     } else {
39         printf("NO");
40     }
41     return 0;
42 }