二叉搜索树的后序遍历序列
1.题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
2.思路
二叉搜索树的后序遍历序列的最后一个元素是根节点,前面小于根节点的部分是左子树,大于根节点的部分是右子树。递归地找出序列中的左子树序列,右子树序列,如果右子树序列比根节点小则返回false。
3.代码
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
if(postorder.empty()){
return true;
}
int root_index = postorder.size() - 1;
int index;
for(index = 0;index < postorder.size();++index){
if(postorder[index] >= postorder[root_index]){
break;
}
}
for(int i = index;i < postorder.size();++i){
if(postorder[i] < postorder[root_index]){
return false;
}
}
vector<int> leftVec(postorder.begin(), postorder.begin() + index);
vector<int> rightVec(postorder.begin() + index, postorder.end() - 1);
bool left = verifyPostorder(leftVec);
bool right = verifyPostorder(rightVec);
return left & right;
}
};
4.复杂度分析
时间复杂度:最坏情况是
O
(
n
2
)
O(n^2)
O(n2)
空间复杂度:
O
(
1
)
O(1)
O(1)