面试题33:二叉搜索树的后序遍历序列
题目
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true
,否则返回 false
。假设输入的数组的任意两个数字都互不相同。
书本版本
bool VerifySquenceOfBST(int sequence[], int length){
if(sequence == nullptr || length <= 0) return false;
int root = sequence[length-1];
int i = 0;
for(;i<length-1;i++){
if(sequence[i] > root)break;
}
int j = i;
for(;j<length-1;j++){
if(sequence[j] < root) return false;
}
bool left = true;
if(i>0) left = VerifySquenceOfBST(sequence,i);
bool right = true;
if(i<length -1) VerifySquenceOfBST(sequence+i,length-1-i);//length-2-(i)+1
return left && right;
}
LeetCode版本
版本1
#include<vector>
using namespace std;
class Solution{
public:
bool core(vector<int> &postOrder, int beginidx, int endidx){
if(beginidx >= endidx ) return true;//这里考虑了两种情况beginidx == endidx 正常收缩, beginidx > endidx 只有右子树的情况
int root = postOrder[endidx];
int leftEnd = beginidx;
for(;leftEnd<endidx;leftEnd++){
if(postOrder[leftEnd] > root) break;
}
int rightBegin = leftEnd;
for(;rightBegin<endidx;rightBegin++){
if(postOrder[rightBegin] < root) return false;
}
return core(postOrder,beginidx,leftEnd-1) && core(postOrder,leftEnd,endidx-1);
}
bool verifyPostorder(vector<int> &postorder){
if(postorder.empty()) return false;
int len = postorder.size();
return core(postorder,0,len-1);
}
};
版本2
class Solution {
public:
bool check(vector<int> &postorder, int begin, int end){
if(begin == end) return true;
int ridx = -1;
int rootval = postorder[end];
for(int i = begin; i < end;i++){
if(postorder[i] > rootval){
ridx = i;
break;
}
}
if(ridx != -1){
for(int j = ridx +1; j<end;j++){
if(postorder[j] < rootval) return false;
}
}
bool res;
if(ridx == -1 || ridx == begin) res = check(postorder,begin,end-1);
else res = check(postorder,begin,ridx-1) && check(postorder,ridx,end-1);
return res;
}
bool verifyPostorder(vector<int>& postorder) {
if(postorder.empty()) return true;//空树定义为是二叉搜索树
int begin = 0, end = postorder.size()-1;
return check(postorder,begin, end);
}
};