解法一:二叉搜索树

思路参考:https://www.liuchuo.net/archives/2153

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. vector<int> preOrder;
  4. vector<int> postOrder;
  5. bool isMirror = false;
  6. void rebuild(int root, int tail) {
  7. if (root > tail)
  8. return;
  9. int i = root + 1, j = tail;
  10. if (!isMirror) {
  11. while (i <= tail && preOrder[root] > preOrder[i])
  12. i++;
  13. while (j > root && preOrder[root] <= preOrder[j])
  14. j--;
  15. } else {
  16. while (i <= tail && preOrder[root] <= preOrder[i])
  17. i++;
  18. while (j > root && preOrder[root] > preOrder[j])
  19. j--;
  20. }
  21. if (i - j != 1)
  22. return;
  23. rebuild(root + 1, j);
  24. rebuild(i, tail);
  25. postOrder.emplace_back(preOrder[root]);
  26. }
  27. int main() {
  28. ios::sync_with_stdio(false);
  29. cin.tie(0);
  30. int N;
  31. cin >> N;
  32. preOrder.resize(N);
  33. for (int i = 0; i < N; ++i) {
  34. cin >> preOrder[i];
  35. }
  36. rebuild(0, N - 1);
  37. if (postOrder.size() != N) {
  38. postOrder.clear();
  39. isMirror = true;
  40. rebuild(0, N - 1);
  41. if (postOrder.size() != N) {
  42. cout << "NO\n";
  43. return 0;
  44. }
  45. }
  46. cout << "YES\n";
  47. cout << postOrder[0];
  48. for (int i = 1; i < N; ++i) {
  49. cout << " " << postOrder[i];
  50. }
  51. cout << "\n";
  52. }