题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
思路:BST:左边节点元素均小于 根节点,右边节点均大于根节点。
递归判断,参数为后续序列,起始下标,终止下标。重写一个递归函数,“单链”时需要单独判断下标是否后大于前。
C++
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
int start = 0, end = sequence.size()-1;
return judgeRearOrder(sequence, start, end);
}
bool judgeRearOrder(vector<int> seq, int s, int e)
{
if(s>e) return false;
if(s==e) return true;
int last = seq[e];
int second_start = s;
for(; second_start<e; ++second_start)
if(seq[second_start]>last)
break;
for(; second_start<e; ++second_start)
{
if(seq[second_start]<last)
return false;
}
// BST只有单侧孩子时要单独判断下标
if(s>second_start-1) return judgeRearOrder(seq, second_start, e-1); //如3 2
if(second_start>e-1) return judgeRearOrder(seq, s, second_start-1); //如1 2
return judgeRearOrder(seq, s, second_start-1) &&
judgeRearOrder(seq, second_start, e-1);
}
};