区间递归 对于起始区间,前序遍历的第一个数的根结点,[root+1,tail]就是root结点的所有结点 对于[root+1,tail]结点因为是二叉搜索树必须满足[root+1,i] < root, [i+1,tail] >= root; 对于镜像二叉搜索树则相反 [root+1,i] >= root [i+1,tail] < root;
如果不满足则返回false; 如果当前满足将 [root+1,tail] 分成 [root+1,i] 和 [i+1,tail] 分别是root的左子树和右子树. 在将这两个区间进行递归。
arr 数组存放的就是后序遍历. - arr 在子树递归完才添加
#include<bits/stdc++.h>
using namespace std;
vector<int> arr1(1005);
vector<int> arr2;
bool tree(int root,int tail)
{
if(root>tail)
return true;
int i=root+1;
int j=tail;
while(i<=tail&&arr1[i]<arr1[root])
i++;
while(j>root&&arr1[j]>=arr1[root])
j--;
if(i!=j+1) //判断是否为二叉搜索树
return false;
if(!tree(root+1,j)) return false;
if(!tree(i,tail)) return false;
arr2.push_back(arr1[root]);
return true;
}
bool treemirror(int root,int tail)
{
if(root>tail)
return true;
int i=root+1,j=tail;
while(i<=tail&&arr1[i]>=arr1[root])
i++;
while(j>root&&arr1[j]<arr1[root])
j--;
if(i!=j+1)
return false;
if(!treemirror(root+1,j)) return false;
if(!treemirror(i,tail)) return false;
arr2.push_back(arr1[root]);
return true;
}
void print()
{
cout<<"YES"<<endl;
int len=arr2.size();
for(int i=0;i<len-1;i++)
cout<<arr2[i]<<" ";
cout<<arr2[len-1];
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr1[i];
}
if(tree(0,n-1))
{
print();
}
else {
arr2.clear();
if(treemirror(0,n-1)) print();
else printf("NO\n");
}
return 0;
}