1. 程式人生 > >劍指Offer-33 二叉搜尋樹的後序遍歷序列

劍指Offer-33 二叉搜尋樹的後序遍歷序列

題目:

輸入一個整數陣列,判斷該陣列是不是某二叉搜尋樹的後序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入的陣列的任意兩個數字都互不相同。

解答:

# -*- coding:utf-8 -*-
class Solution:
    def VerifySquenceOfBST(self, sequence):
        if not sequence:
            return False
        if len(sequence) <= 2:
            return True
        return self.
check(sequence, 0, len(sequence)-2, len(sequence)-1) def check(self, sequence, start, end, rootIndex): root = sequence[rootIndex] i, j = start, end while(sequence[i] < root): i += 1 while(sequence[j] > root): j -= 1 if j + 1 !=
i: return False if j - 1 > start and i < end - 1: return self.check(sequence, start, j - 1, j) and self.check(sequence, i, end - 1, end) if j - 1 <= start and i < end - 1: return self.check(sequence, i, end - 1, end) if j - 1 >
start and i >= end - 1: return self.check(sequence, start, j - 1, j) return True