题目:
题目链接: https://leetcode-cn.com/problems/validate-binary-search-tree/
解题思路:
从底向上的判断每个节点的左右子树和自己的值大小,如果不符合二叉搜索数的要求,返回false,结束所有递归;如果符合要求,将当前的值列表返回给上一层,继续递归
代码实现:
# 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:
def valid_help(root, path):
if not root:
return True
left = []
if root.left and False == valid_help(root.left, left):
return False
right = []
if root.right and False == valid_help(root.right, right):
return False
if 0 < len(left) and max(left) >= root.val:
return False
elif 0 < len(right) and min(right) <= root.val:
return False
path += left + right + [root.val]
return True
return valid_help(root, [])