题目:
思路+代码:
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
# 递归法
# 1.递归结束条件:直到叶子节点,没有左右子树,此时i=j,此时表示True,符合二叉搜索树
# 2.递归推导:从头到尾找到第一个大于root节点的值;然后判断从这个值开始是不是后面序列都大于root值,然后分布对左子树和右子树进行递归
# 3.返回值:判断左指针是否指到root,返回左子树递归结果和右子树递归结果
def recur(i, j, postorder):
if i >= j: # 为什么是大于?
return True
start = i
while postorder[i] < postorder[j]: i += 1
m = i # 右子树第一个节点
while postorder[i] > postorder[j]: i += 1
return i==j and recur(start, m-1, postorder) and recur(m, j-1, postorder)
return recur(0, len(postorder)-1, postorder)