使用预订遍历验证二进制树

发布于 2025-02-08 12:38:52 字数 1371 浏览 1 评论 0原文

我正在寻找leetcode问题 98。验证二进制搜索树

给定二进制树的root确定它是否是有效的二进制搜索树(BST)

a 有效的BST 定义如下:

  • 节点的左子树仅包含键的节点小于节点键。
  • 节点的右子树仅包含键的节点大于 节点键。
  • 左右子树都必须是二进制搜索树。

下面提供的代码以使用预订遍历验证二进制树属性有什么问题?

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def preorder(root):
        
            if root.left!=None:
                if root.left < root.val:
                    preorder(root.left)
                else:
                    return False
            
        
            if root.right!=None:
                if root.right>root.val:
                    preorder(root.right)
                else:
                    return False
       
    t= preorder(root)
    return t!=False

它正在返回false的测试用例,其中root = [2,1,3]

I am looking at LeetCode problem 98. Validate Binary Search Tree:

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

What is the problem with the below provided code for validating the binary tree property with preorder traversal?

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def preorder(root):
        
            if root.left!=None:
                if root.left < root.val:
                    preorder(root.left)
                else:
                    return False
            
        
            if root.right!=None:
                if root.right>root.val:
                    preorder(root.right)
                else:
                    return False
       
    t= preorder(root)
    return t!=False

It is returning False for the Test case where root=[2,1,3]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橙味迷妹 2025-02-15 12:38:52

仅在 时,您才需要穿越右sub-tree

       def preorder(root):
            if root.left!=None:
                if root.left < root.val:
                    preorder(root.left)
                else:
                    return False
            
        
            if root.right!=None (and left-sub-tree is valid):
                if root.right>root.val:
                    preorder(root.right)
                else:
                    return False

注意:我不知道Python。在检查右手树时了解评论。

You need to traverse the right-sub-tree only when the left-sub-tree is a valid one.

       def preorder(root):
            if root.left!=None:
                if root.left < root.val:
                    preorder(root.left)
                else:
                    return False
            
        
            if root.right!=None (and left-sub-tree is valid):
                if root.right>root.val:
                    preorder(root.right)
                else:
                    return False

Note: I don't know Python. Understand the comment while checking right-sub-tree.

雪若未夕 2025-02-15 12:38:52

几个问题:

  • root.left&lt; root.val将A node 与整数进行比较。这应该是root.left.val&lt; root.val。右侧检查相同。

  • 预订返回false在发生违规时,呼叫者会使递归调用忽略此返回值并愉快地继续。这是错误的。当递归调用返回false,并且本身返回false时,它应该停止遍历。

  • 不是主要问题,而是预订返回false,它应该更好地返回true,因此您可以确定预订返回布尔值,不必对无需或将返回值明确比较false> false

  • 该算法仅检查节点的直接子是否具有与父母价值不冲突的值,但这还不足以验证BST。 左子树中的所有值必须小于父母的价值,而不仅仅是左子女。因此,即使上述问题已解决,该算法也会错误地说该BST有效:

      4
     /
    1
     \ \
      9&lt;  - 违规(由于4)
     

要解决最后一点,您需要修改算法:意识到当您在BST中深处时,就会有一个窗口< /em>在有效BST中的子树的值可以具有:有下限和上限。在上面的示例中,节点1的右子只能在范围内具有值(1,4)。

这是一个破坏者的实现:

类解决方案(对象):
def isvalidbst(self,root):
def预订(根,低,高):
返回不root或((
低&lt; root.val&lt;高
预订(left,low,low,root.val)和
预订(root.right,root.val,高)

返回预订(root,-float(“ inf”),float(“ inf”))

Several issues:

  • root.left < root.val is comparing a node with an integer. This should be root.left.val < root.val. Same for the right side check.

  • Although preorder returns False when there is a violation, the caller that makes the recursive call ignores this return value and happily continues. This is wrong. It should stop the traversal when the recursive call returns False, and itself return False to its caller.

  • Not the main issue, but as preorder returns False, it should better return True in the remaining cases, so you can be sure that preorder returns a boolean, and don't have to treat None or compare the return value explicitly with False.

  • The algorithm only checks whether a direct child of a node has a value that is not conflicting with the value of the parent, but that is not enough for validating a BST. All the values in the left subtree must be less than parent's value, not just the left child. So even if the above problems are fixed, this algorithm will wrongly say this BST is valid:

      4
     /
    1
     \
      9  <-- violation  (because of 4)
    

To solve the last point, you need to revise the algorithm: realise that when you are deep in a BST, there is a window of values that a subtree in a valid BST can have: there is a lower limit and an upper limit. In the above example the right child of the node 1 could only have a value in the range (1, 4).

Here is an implementation as a spoiler:

class Solution(object):
def isValidBST(self, root):
def preorder(root, low, high):
return not root or (
low < root.val < high and
preorder(root.left, low, root.val) and
preorder(root.right, root.val, high)
)

return preorder(root, -float("inf"), float("inf"))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文