此题理解起来很简单,关键操作在于:当前节点满足二叉搜索树根节点的条件是节点值大于左子树中最右的节点值(在左子树满足二叉搜索树的前提下);同时节点值还要小于右子树的最左节点值(在右子树满足二叉搜索树的前提下)。
代码:
# 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 is None: return True
if root.left is None and root.right is None: return True
L = root.left
if L is not None:
while(L.right): L = L.right
R = root.right
if R is not None:
while(R.left): R = R.left
if L is None:
return root.val < R.val and self.isValidBST(root.right)
if R is None:
return root.val > L.val and self.isValidBST(root.left)
return root.val > L.val and root.val < R.val and self.isValidBST(root.right) and self.isValidBST(root.left)