【问题标题】:Validate a binary search tree using recursion使用递归验证二叉搜索树
【发布时间】:2021-12-15 20:16:00
【问题描述】:

我正在尝试验证二叉搜索树。给定二叉树的根,判断它是否是有效的二叉搜索树(BST)。

一个有效的 BST 定义如下:

节点的左子树只包含键小于节点键的节点。 节点的右子树只包含键大于节点键的节点。 左右子树也必须是二叉搜索树。

https://leetcode.com/problems/validate-binary-search-tree/

我正在使用递归解决方案,但未能通过此测试用例:
输入:[2,1,3]
预期输出:真
我的输出:假

示例输入示例:[5,1,4,null,null,3,6]
预期输出:假
我的输出:假

谁能指出我的错误?以下是我的代码:

# 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"))

【问题讨论】:

  • 你能更好地解释一下测试用例吗?
  • 请检查。我已经编辑了问题并添加了一些示例输入和输出

标签: python data-structures tree


【解决方案1】:

您可以通过为递归中的左右节点提供一系列值来下推验证。这样,每个节点只需根据其父节点传递的要求检查自己,然后递归其自己的子节点。

def isBST(node,minVal=None,maxVal=None):
    if node is None: return True
    if minVal is not None and self.val<minVal: return False 
    if maxVal is not None and self.val>maxVal: return False
    if not isBST(self.left,minVal,self.val):   return False
    if not isBST(self.right,self.val,maxVal):  return False
    return True

【讨论】:

    【解决方案2】:

    其实,你离得并不远。您只是错过了一个地方 - 请参阅代码:

    这是相同的想法,但代码略有不同以匹配您的原始。逻辑并与您的帖子进行比较。

    [Note] 受 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!
         
    

    【讨论】:

    • 我觉得写“+inf”比较好,突出区别。
    • 已记笔记。谢谢。
    猜你喜欢
    • 2014-01-02
    • 2021-07-03
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2013-04-21
    • 1970-01-01
    相关资源
    最近更新 更多