原题链接:剑指offer JZ33 二叉搜索树的后序遍历序列
思想1:分治
1.二叉树的后序遍历顺序是:左子树 -> 右子树 -> 根节点,因此序列的最后一个数代表了根节点
2. 我们可以将一个序列划分为3段, 左子树+右子树+根, 例如[4, 8, 6, 12, 16, 14, 10]可以根据根节点的值将其划分为左子树[4, 8, 6], 右子树[12, 16, 14], 根[10], 由于我们是先确定的右子树区间, 因此当左子树区间中出现大于根节点的值时, 序列不合法, 我们再采用分治的思想, 对于每段序列代表的子树, 检查它的左子树和右子树, 当且仅当左右子树都合法时返回true
class Solution {
public:
bool check(vector<int>& sequence,int l,int r)
{
if(l>=r)// 若当前子树只有一个节点
return true;
int root=sequence[r];// 当前子树的根节点
int j=r-1;
// 划分出右子树
while(j>=0 && sequence[j]>root)
j--;
// 检查左子树是不是存在大于根节点的数
for(int i=l;i<=j;i++)
{
if(sequence[i]>root)
return false;
}
// 分治法检查左子树和右子树
return check(sequence,l,j) && check(sequence,j+1,r-1);
}
bool VerifySquenceOfBST(vector<int> sequence) {
int n=sequence.size();
if(!n)
return false;
return check(sequence,0,n-1);
}
};
思想2:栈
1.实际上二叉树的中序遍历和后序遍历对应着一种栈的压入、弹出序列, 而对后序遍历序列从小到大排序就得到了中序遍历序列
2.我们得到中序遍历序列后, 将其作为入栈序列, 检查后序遍历序列是不是一个合法的出栈序列即可
3.对于检查栈的合法压入、弹出序列问题, 请看剑指offer JZ31 栈的压入、弹出序列
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.size()==0)
return false;
vector<int> inorder(sequence);
sort(inorder.begin(),inorder.end());
stack<int> s;
int i=0,j=0;
while(i<inorder.size())
{
if(inorder[i]!=sequence[j])
{
s.push(inorder[i++]);
}
else
{
i++;j++;
while(!s.empty() && s.top()==sequence[j])
{
s.pop();j++;
}
}
}
return s.empty();
}
};