误区:单独判断某一个子树是否满足搜索树是不够的
class Solution:
def isValidBST(self , root: TreeNode) -> bool:
# write code here
if not root:
return True
if root.left and root.left.val >= root.val:
return False
if root.right and root.right.val <= root.val:
return False
else:
return self.isValidBST(root.right) and self.isValidBST(root.left)
解法:如果一个数是搜索树,则它的中序遍历一定是一个递增数列
class Solution:
def isValidBST(self , root: TreeNode) -> bool:
# write code here
# 中序遍历判断是否为单调增序列
node_list = self.midOrder(root)
for i in range(len(node_list) - 1):
if node_list[i] >= node_list[i + 1]:
return False
return True
def midOrder(self, node: TreeNode) -> list[int]:
if not node:
return []
return self.midOrder(node.left) + [node.val] + self.midOrder(node.right)