【问题标题】:Determine if BST确定是否 BST
【发布时间】:2017-07-14 20:35:22
【问题描述】:
class BTNode:
    """Binary Tree node."""
    def __init__(self: ’BTNode’, data: object,
                 left: ’BTNode’=None, right: ’BTNode’=None) -> None:
      """Create BT node with data and children left and right."""
      self.data, self.left, self.right = data, left, right

 def is_bst(t: BTNode) -> bool:

   if not t:
     return False
   if not t.left and not t.right:
     return True
   if t.left and t.right:
     if not(t.data > t.left.data) or not(t.data < t.right.data):
       return False
   else:
     return is_bst(t.left) and is_bst(t.right)

函数描述说,如果以 t 为根的二叉树具有 BST 属性,则返回 True。

is_bst(BTNode(8, BTNode(9, BTNode(2, None, None), BTNode(6, None, None)),\
BTNode(10, None, None)))

以下调用在应该返回 False 时返回 True,因为左分支中的 9 大于根值 8。这违反了 BST 属性

我不确定为什么会得到这个输出。你能告诉我我的功能有什么问题吗?

谢谢

【问题讨论】:

    标签: python-3.x binary-search-tree


    【解决方案1】:

    你的逻辑是倒退的。

    例如,您检查 t.left,然后返回 True。但在这种情况下,您永远不会检查 t.right。

    当 t.left 检查失败时,您只需检查 t.right,并可能返回 true,忽略 t.left 上的失败。

    相反,您应该寻找失败。基本上,您所做的每个返回都应该是一个return False,并且只有当所有测试通过时,您才会在最后返回 true。

    if something wrong with t:
        return False
    if something wrong with t.data:
        return False
    if something wrong with t.left:
        return False
    if something wrong with t.right:
        return False
    
    # Apparently, nothing is wrong
    return True
    

    【讨论】:

    • 但我不确定如何使代码以这种方式递归
    • 最后你有一个递归调用。我很好。我只是希望您将所有测试都转换为否定测试-寻找问题。除了(可能)最后一个返回 False 之外,您的所有返回都返回 False,因为您发现了问题。只有当你发现没有问题时,你才应该返回 True。看看你能不能把它分解成“这里有问题吗?”输入问题。
    【解决方案2】:

    回答这个问题:

    我不确定为什么会得到这个输出。

    根节点 (8) 确实小于其右子节点 (10) - 您的第四个 if 语句正在检查它。结果,该函数返回了True,而没有对您提供的树进行任何递归。

      if t.right:
         if t.data < t.right.data:
            return True
    

    回答这个问题:

    你能告诉我我的功能有什么问题吗?

    与另一个答案类似,通过检查返回 False 的机会来检查树中是否存在故障会更容易。我写得很快(还没有测试过),但它会使用递归对树进行“预定”遍历。

    if not t:
        return False
    
    if t.left:
        if t.data > t.left.data:
            return is_bst(t.left)
        else:
            return False
    
    if t.right:
        if t.data < t.right.data:
            return is_bst(t.right)
        else:
            return False
    
    return True
    

    【讨论】:

      猜你喜欢
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 2022-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多