牛客网&剑指Offer&二叉搜索树的后序遍历
代码实现
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.size() == 0)
return false;
int len = 0;
int Lindex = 0;
int Rindex = 0;
int RootValue = 0;
vector<int> leftvec;
vector<int> rightvec;
len = sequence.size();
RootValue = sequence[len-1];
for( ; Lindex < len; ++Lindex)
{
if(sequence[Lindex] > RootValue)
break;
}
Rindex = Lindex + 1;
for( ; Rindex < len; ++Rindex)
{
if(sequence[Rindex] < RootValue)
return false;
}
bool leftflag = true;
if(Lindex > 0)
{
for(int i = 0; i <= Lindex; i++)
{
leftvec.push_back(sequence[i]);
}
VerifySquenceOfBST(leftvec);
}
bool rightflag = true;
if(Rindex < len - 1)
{
for(int i = Lindex + 1; i <= len; i++)
{
rightvec.push_back(sequence[i]);
}
VerifySquenceOfBST(rightvec);
}
return (leftflag && rightflag);
}
};
代码实现&错误:内存超限:您的程序使用了超过限制的内存
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if (sequence.size() == 0)
return false;
int len = 0;
int Lindex = 0;
int Rindex = 0;
int RootValue = 0;
vector<int> leftvec;
vector<int> rightvec;
len = sequence.size();
RootValue = sequence[len - 1];
for (; Lindex < len; ++Lindex)
{
leftvec.push_back(sequence[Lindex]);
if (sequence[Lindex] > RootValue)
break;
}
Rindex = Lindex + 1;
for (; Rindex < len; ++Rindex)
{
rightvec.push_back(sequence[Lindex]);
if (sequence[Rindex] < RootValue)
return false;
}
bool leftflag = true;
VerifySquenceOfBST(leftvec);
bool rightflag = true;
VerifySquenceOfBST(rightvec);
return (leftflag && rightflag);
}
};
编程笔记
- 代码实现解题思路:1.明确搜索二叉树的性质;2.后序遍历,则最后一个数字为根节点的值。3.根据搜索二叉树的性质将数组的大小划分为两部分,比根节点划分为小的划分为左子树部分,另一部分为右子树部分,此时判断右子树部分是否有小于根节点数值的值,若有则该树并不是搜索二叉树。4.将左子树以及右子树循环递归执行操作3。
- 二叉树搜索的性质
二叉搜索树性质参考链接