第一个条件 等价于 左子树的最右节点 < 当前节点
第二个条件 等价于 右子树的最左节点 > 当前节点
第三个条件 递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if root == None:
return True
res1 = True if (root.left is None or (self.findlowest(root.left,'right').val < root.val)) else False
res2 = True if (root.right is None or (self.findlowest(root.right,'left').val > root.val)) else False
return self.isValidBST(root.left) and self.isValidBST(root.right) and res1 and res2
def findlowest(self,thisroot,direction):
if direction == 'left':
return self.findlowest(thisroot.left,'left') if thisroot.left != None else thisroot
elif direction == 'right':
return self.findlowest(thisroot.right,'right') if thisroot.right != None else thisroot