参考资料:
[1]二叉查找树的概念:http://www.cnblogs.com/skywang12345/p/3576373.html
[2]递归的终止条件:https://blog.csdn.net/sinat_38052999/article/details/73303111
关键词:
思路:
1判断左子树是不是二叉搜索树的后序遍历数列
2判断右子树是不是二叉搜索树的后序遍历数列
3左子树和右子树都是二叉搜索树的后序遍历数列,那么就是二搜索树的后序遍历数列
举例说明:
自己的解答:
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
//异常判断
if(sequence.size()==0)
return false;
//如何得到左子树
vector<int> lefttree;
int root = sequence[sequence.size()-1];
int i=0;
for(;i<sequence.size()-1;i++)
{
if(sequence[i]>root)//左子树都是小于根节点
break;
lefttree.push_back(sequence[i]);
}
//如何得到右子树
vector<int> righttree;
for(;i<sequence.size()-1;i++)
{
if(sequence[i]<root)//右子树有小于根节点的,那就是错误的
return false;
righttree.push_back(sequence[i]);
}
bool left = true;
bool right = true;
//1判断左子树是不是二叉搜索树的后序遍历数列
if(lefttree.size() >=1)
left = VerifySquenceOfBST(lefttree);
//2判断右子树是不是二叉搜索树的后序遍历数列
if(righttree.size() >=1)
right = VerifySquenceOfBST(righttree);
//3左子树和右子树都是二叉搜索树的后序遍历数列,那么就是二搜索树的后序遍历数列
bool result = left&&right;
return result;
}
};
标准答案:
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.size() ==0)
return false;
//1.取出根节点值
int size = sequence.size();
int root = sequence[size-1];
//新建两个子树序列
vector<int> lefttree;
vector<int> righttree;
//2.判断左子树,要求他的值是小于根节点的值
int i=0;
for(;i<=(size-2);i++)//注意遍历的范围!!!!!
{
if(sequence[i]>root)
break;
lefttree.push_back(sequence[i]);
}
//3.判断右子树,要求他的值大于根节点的,如果小于的话,那就不是,直接返回 false
int j =i;
for(;j<=(size-2);j++)//注意遍历的范围!!!!!
{
if(sequence[j]<root)
return false;
righttree.push_back(sequence[j]);
}
//4.如何判断左子树
bool left = true;//注意默认的值,得为true!!!!
if(i >= 1)//注意左子树不为空才行!!!!
left = VerifySquenceOfBST(lefttree);
//5.如何判断右子树
bool right = true;//注意默认的值,得为true
if(i<=(size-3))//注意右子树不为空才行!!!
right = VerifySquenceOfBST(righttree);
return left&&right;
}
};