验证某个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])

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容