驗證某個list是搜索二叉樹的后序遍歷序列

問題參考:《劍指offer》24題
注意:python中data[xxx:yyy]是從xxx到yyy-1的那幾個數而不是xxx到yyy
課本上的舉一反三說的非常好,處理一棵二叉樹的遍歷序列都是要將其分開來,然后遞歸處理

def is_post_travel(data):
    length = len(data)
    #方便調試和查看遞歸過程
    print(data)
    if length <= 1:
        return True

    root_num = data[length - 1]

    i = 0
    while i < (length-1) and data[i] < root_num:
        i += 1

    rchild_index = i

    while i < (length-1) and data[i] > root_num:
        i += 1

    if i != length - 1:
        return False

    return is_post_travel(data[:rchild_index]) and is_post_travel(data[rchild_index:length-1])

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容