參考資料:
[1]二叉查找樹的概念:http://www.cnblogs.com/skywang12345/p/3576373.html
[2]遞歸的終止條件:https://blog.csdn.net/sinat_38052999/article/details/73303111
關(guān)鍵詞:
思路:
1判斷左子樹是不是二叉搜索樹的后序遍歷數(shù)列
2判斷右子樹是不是二叉搜索樹的后序遍歷數(shù)列
3左子樹和右子樹都是二叉搜索樹的后序遍歷數(shù)列貌矿,那么就是二搜索樹的后序遍歷數(shù)列
舉例說明:
自己的解答:
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)//左子樹都是小于根節(jié)點(diǎn)
break;
lefttree.push_back(sequence[i]);
}
//如何得到右子樹
vector<int> righttree;
for(;i<sequence.size()-1;i++)
{
if(sequence[i]<root)//右子樹有小于根節(jié)點(diǎn)的拥刻,那就是錯(cuò)誤的
return false;
righttree.push_back(sequence[i]);
}
bool left = true;
bool right = true;
//1判斷左子樹是不是二叉搜索樹的后序遍歷數(shù)列
if(lefttree.size() >=1)
left = VerifySquenceOfBST(lefttree);
//2判斷右子樹是不是二叉搜索樹的后序遍歷數(shù)列
if(righttree.size() >=1)
right = VerifySquenceOfBST(righttree);
//3左子樹和右子樹都是二叉搜索樹的后序遍歷數(shù)列虚倒,那么就是二搜索樹的后序遍歷數(shù)列
bool result = left&&right;
return result;
}
};
標(biāo)準(zhǔn)答案:
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.size() ==0)
return false;
//1.取出根節(jié)點(diǎn)值
int size = sequence.size();
int root = sequence[size-1];
//新建兩個(gè)子樹序列
vector<int> lefttree;
vector<int> righttree;
//2.判斷左子樹,要求他的值是小于根節(jié)點(diǎn)的值
int i=0;
for(;i<=(size-2);i++)//注意遍歷的范圍3雅琛!!8韪取!
{
if(sequence[i]>root)
break;
lefttree.push_back(sequence[i]);
}
//3.判斷右子樹骑晶,要求他的值大于根節(jié)點(diǎn)的痛垛,如果小于的話,那就不是桶蛔,直接返回 false
int j =i;
for(;j<=(size-2);j++)//注意遍歷的范圍3淄贰!W欣住u逦觥!
{
if(sequence[j]<root)
return false;
righttree.push_back(sequence[j]);
}
//4.如何判斷左子樹
bool left = true;//注意默認(rèn)的值,得為true5拧5绺А!竖共!
if(i >= 1)//注意左子樹不為空才行蝙叛!!!!
left = VerifySquenceOfBST(lefttree);
//5.如何判斷右子樹
bool right = true;//注意默認(rèn)的值,得為true
if(i<=(size-3))//注意右子樹不為空才行!V庥甥温!
right = VerifySquenceOfBST(righttree);
return left&&right;
}
};