L2-004. 这是二叉搜索树吗?
首先可以知道的是通过递归可以对应出后序遍历的序列,看其是否长度相等。。。
这其中用到一些性质自己画一画就能理解!!!
#include<iostream>
#include<vector>
#include<map>
using namespace std;
#define MAXN 1005
vector<int>post;
vector<int>pre;
int n;
bool is = true;
void getroots(int la, int ra) {
if(la > ra) return ;
int i = la + 1, j = ra;
if(is) {
while(i <= ra&&pre[la] > pre[i]) i++;
while(j > la&&pre[la] <= pre[j]) j--;
} else {
while(i <= ra&&pre[la] <= pre[i]) i++;
while(j > la&&pre[la] > pre[j]) j--;
}
if(i - j != 1) return ;
getroots(la + 1, j);
getroots(i, ra);
post.push_back(pre[la]);
}
int main()
{
cin >> n;
pre.resize(n);
for(int i = 0; i < n; i++) cin >> pre[i];
getroots(0, n-1);
if(post.size() != n) {
is = false;
post.clear();
getroots(0, n-1);
}
if(post.size() != n) {
cout << "NO" << endl;
} else {
cout << "YES" << endl;
cout << post[0];
for(int i = 1; i < n; i++) {
cout << " " << post[i];
}
cout << endl;
}
}