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

你可能感兴趣的:(验证某个list是搜索二叉树的后序遍历序列)