题目来源:46. 二叉搜索树的后序遍历序列
什么是二叉搜索树(BST)?
它或者是一棵空树,或者是具有下列性质的二叉树:
后序遍历序列的最后一个值是二叉树的根节点。
二叉搜索树的后序遍历序列的前面的值一部分小于根节点,一部分大于根节点。
算法:
代码:
class Solution
{
public:
bool verifySequenceOfBST(vector<int> sequence)
{
// 特判
if (sequence.size() <= 1)
return true;
return postOfBST(sequence, 0, sequence.size() - 1);
}
// 辅函数 - 递归判断
bool postOfBST(vector<int> &sequence, int begin, int end)
{
if (begin >= end)
return true;
int splitIndex = begin, rootValue = sequence[end];
while (splitIndex < end && sequence[splitIndex] <= rootValue)
splitIndex++;
for (int i = splitIndex; i < end; i++)
if (sequence[i] < rootValue)
return false;
return postOfBST(sequence, begin, splitIndex - 1) && postOfBST(sequence, splitIndex, end - 1);
}
};
复杂度分析:
时间复杂度:O(n),其中 n 是二叉树的节点个数。
空间复杂度:O(depth),其中 depth 是二叉树的深度。