#include<iostream> #include<vector> usingnamespacestd; vector<int> post, arr; bool flag; //初始假设为二叉搜索树 //如果能成功转换的话就可以 voidPost(int root, intend){ if (root > end) return; int i = root + 1; int j = end; //需要确定左右子树的头尾 即确定左子树的尾 和 右子树的头 if (!flag) { while (i <= end && arr[i] < arr[root]) i++; //找右子树的头 while (j > root && arr[root] <= arr[j]) j--; //找左子树的尾 } else { //镜像二叉 while (i <= end && arr[root] <= arr[i]) i++; //找右子树的头 while (j > root && arr[j] < arr[root]) j--; //找左子树的尾 }
//根据后序遍历 左右根 的顺序 if (i - j != 1) return; Post(root + 1, j); Post(i, end); post.push_back(arr[root]); }
intmain(){ int n; scanf("%d", &n);arr.resize(n); for(int i = 0; i < n; i++) scanf("%d", &arr[i]);
//先看看是不是二叉搜索树 Post(0, n - 1); if (post.size() != n) { flag = true; post.clear(); Post(0, n - 1); } if (post.size() == n) { printf("YES\n%d", post[0]); for (int i = 1; i < n; i++) printf(" %d", post[i]);