二叉搜索树的后序遍历序列

二叉搜索树的后序遍历序列

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值