1.题目
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
2.Code
后序遍历数组,则最后一个数是树的根节点,又因为是一棵BST,则比这个数小的都是左子树,比其大的都是个右子树上的节点。所以递归解决即可。
注意数组为空的状态和边界条件的检查
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
int len = sequence.size();
return judge_bst(sequence,0,len-1);
}
private:
bool judge_bst(vector<int> sequence,int left, int right)
{
if(sequence.empty() || left > right)
return false;
int root = sequence[right];
int i,j;
//找到左子树的边界点
for(i = 0; i < right; ++i){
if(sequence[i] > root)
break;
}
//判断右子树中是否有小于根节点的值有就返回false
for(j = i; j < right; ++j){
if(sequence[j] < root)
return false;
}
//判断左子树是不是二叉树
bool res1 = true;
if(i > 0)
res1 = judge_bst(sequence,0,i-1);
//判断右子树是不是二叉树
bool res2 = true;
if(i < right-1)
res2 = judge_bst(sequence,i,right-1);
return res1 && res2;
}
};