剑指offer33 二叉搜索树的后序遍历序列

剑指offer33 二叉搜索树的后序遍历序列

    输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。

    如果是则返回true,否则返回false。

    假设输入的数组的任意两个数字都互不相同。

样例

输入:[4, 8, 6, 12, 16, 14, 10]

输出:true

思路

    二叉搜索树的后序遍历,最后一个结点为头节点,数组可以分为两部分,连续的小于头节点结点为左子树,连续的大于头节点的为右子树。可递归继续判断左右子树是否符合条件。

AcWing-46 C++ code

class Solution {
public:
    bool verifySequenceOfBST(vector<int> sequence) {
        vector<int> left_sequence, right_sequence;
        if(sequence.empty()){
            return true;
        }
        int n = sequence.size();
        int i = 0;
        for(; i < n - 1; i++){
            if(sequence[n - 1] > sequence[i]){
                left_sequence.push_back(sequence[i]);
            }else{
                break;
            }
        }
        for(; i < n - 1; i++){
            if(sequence[n - 1] < sequence[i]){
                right_sequence.push_back(sequence[i]);
            }else{
                return false;
            }
        }
        
        return verifySequenceOfBST(left_sequence) && verifySequenceOfBST(right_sequence);
          
    }
};

AcWing-46 python code

class Solution:
    def verifySequenceOfBST(self, sequence):
        """
        :type sequence: List[int]
        :rtype: bool
        """
        if len(sequence) == 0:
            return True
        
        n = len(sequence)
        
        i = 0
        while sequence[i] < sequence[-1]:
            i += 1
            
        for j in sequence[i:-1]:
            if sequence[-1] > j:
                return False
        
        return self.verifySequenceOfBST(sequence[:i]) and self.verifySequenceOfBST(sequence[i:-1])      

你可能感兴趣的:(剑指offer,剑指offer,算法,python,c++)