LeetCode刷题笔记17
剑指 Offer 33. 二叉搜索树的后序遍历序列
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
提示:
数组长度 <= 1000
思路
数组长度小于等于2的情况下均返回True
其他情况:
根节点为数组最后一个数,接着找数组中第一个大于root.val的数的索引,由此分出左右子树,如果左子树的最大值大于root.val或者右子树的最小值小于root.val均返回false。然后递归调用函数查看左右子树是否满足后序遍历
代码
class Solution(object):
def verifyPostorder(self, postorder):
"""
:type postorder: List[int]
:rtype: bool
"""
if len(postorder)<=2:
return True
root_val=postorder[-1]
for i in range(len(postorder)):
if(postorder[i])>root_val:
break
left=postorder[:i]
right=postorder[i:-1]
left_res=True
right_res=True
if len(left)>0:
if max(left)>root_val:
return False
left_res=self.verifyPostorder(left)
if len(right)>0:
if min(right)<root_val:
return False
right_res=self.verifyPostorder(right)
return left_res and right_res