python - 使用递归验证二叉搜索树
问题描述
我正在尝试验证二叉搜索树。给定二叉树的根,确定它是否是有效的二叉搜索树 (BST)。
有效的 BST 定义如下:
节点的左子树仅包含键小于节点键的节点。节点的右子树只包含键大于节点键的节点。左右子树也必须是二叉搜索树。
https://leetcode.com/problems/validate-binary-search-tree/
我正在使用递归解决方案,但未能通过此测试用例:
输入:[2,1,3]
预期输出:真
我的输出:假
示例输入示例:[5,1,4,null,null,3,6]
预期输出:False
我的输出:False
有人可以找出我的错误吗?下面是我的代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def valid(node, left, right):
if not node:
return True
if not (node.val>left and node.val<right):
return False
return (valid(node.left, left, node.val) and valid(node.right, node.val, right))
return valid(root, float("-inf"), float("-inf"))
解决方案
其实,你离得并不远。您只是错过了一个地方 - 请参阅代码:
这是相同的想法,但代码略有不同以匹配您的原始。逻辑并与您的帖子进行比较。
[注] 受 Alain 和 OP 递归思想的启发。所以归功于他们。;-)
def isValidBST(self, root: TreeNode) -> bool:
def validate(node, lower, upper):
if not node: return True # empty node/Tree considered BST
# compare the node range is still valid: between low and high
if node.val > lower and node.val < upper:
return validate(node.left, lower, node.val) and \
validate(node.right, node.val, upper)
return False
return validate(root, float("-inf"), float("+inf")) # <--- miss here!
推荐阅读
- c++ - HDFql 保存和加载图像
- php - 如何解决codeigniter中的分页问题
- sharepoint - Sharepoint 产品配置在 3 个任务中失败异常:System.NullReferenceException:对象引用未设置为对象的实例
- python - Python csv:将列拆分为列,然后按分隔符拆分为行
- c# - 如何在内存中运行时修改程序集中的类
- php - 为自定义身份验证流程获取“NotAuthorizedException 不正确的用户名或密码”
- css - 如何在字体属性中设置多个字体大小?
- javascript - WorkerGlobalScope 中未定义的 Window.top
- reactjs - 在响应中单击随机 div 时向父组件发送数据
- django - 如何在 Django 应用程序中用 react ContextAPI 替换 Redux