从根节点开始递归 | #二叉搜索树的后序遍历序列#
二叉搜索树的后序遍历序列
https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param sequence int整型一维数组 # @return bool布尔型 # class Solution: def VerifySquenceOfBST(self , sequence: list[int]) -> bool: # write code here if not sequence: return False else: return self._verify_rec(sequence) def _verify_rec(self , sequence: list[int]): # print(sequence) if len(sequence) == 0: return True elif len(sequence) == 1: return True else: root_node = sequence[-1] sequence = sequence[:-1] into_right = 0 left_bound = 0 for i in range(len(sequence)): if sequence[i] == root_node: return False elif (not into_right) and sequence[i] > root_node: into_right = 1 left_bound = i+0 elif into_right and sequence[i] < root_node: return False if not into_right: left_bound = len(sequence)-1 return self._verify_rec(sequence[:left_bound]) and self._verify_rec(sequence[left_bound:])