输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
class Solution {
public:
bool pdecsss(vector<int>& postorder, int left, int right){
//终止条件
if(left>=right) return true;
int pos=left;
//int len = postorder.size();
for(;pos<right;pos++){
if(postorder[pos]>postorder[right])
break;
}
for(int i=pos;i<right; i++){
if(postorder[i]<postorder[right]) return false;
}
//等价关系
if(!pdecsss(postorder, left, pos-1)) return false;
if(!pdecsss(postorder, pos,right-1)) return false;
return true;
}
bool verifyPostorder(vector<int>& postorder) {
if(postorder.empty()) return true;
int left=0;
int right =postorder.size()-1;
return pdecsss(postorder, left, right);
}
};
/*
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
if(postorder.empty()) return true;
int len = postorder.size();
return recursion(postorder, 0, len - 1);
}
bool recursion(vector<int>& postorder, int left, int right)
{
if(left >= right) return true; // 没有左子树(比如[5,4,3,2,1]),true
int root = postorder[right];
int pos = left; // 必须要设置一个 pos 变量保存 left,不能直接操作 left!
for(; pos<right; ++pos)
{
// 找到右子树起点
if(postorder[pos] > root) break;
}
for(int j=pos; j<right; ++j)
{
// 如果右子树部分有小于 root 的,false
if(postorder[j] < root) return false;
}
// 看左子树是否也是后序遍历。如果前面不设置 pos 的话,这里就会是 (postorder,0,left-1),会严重超时
if(!recursion(postorder, left, pos - 1)) return false;
if(!recursion(postorder, pos, right - 1)) return false;// 看右子树是否也是后序遍历
return true;
}
};
*/