题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
解题思路:
对于BST的后序序列,最后一个元素即为根节点, 根节点的左子树为数组前段,右子树为数组后段;
AC C++ Solution:
class Solution {
public:
/* 对于BST的后序序列,最后一个元素即为根节点, 根节点的左子树为数组前段,右子树为数组右段*/
bool judge(vector<int> nums, int l, int r) {
if(l >= r)
return true;
int i = r;
while(i > l && nums[i-1] > nums[r]) //找到第一个小于根节点的元素,即为左子节点
i--;
for(int j = i-1; j >= l; --j) //判断左子树是否都小于根节点
if(nums[j] > nums[r])
return false;
return judge(nums,l,i-1) && judge(nums,i,r-1); //递归
}
bool VerifySquenceOfBST(vector<int> sequence) {
int n = sequence.size();
if(n == 0)
return false;
return judge(sequence,0,n-1);
}
};