【问题标题】:Function to determine whether tree is a valid BST?确定树是否是有效的 BST 的函数?
【发布时间】:2017-05-20 08:47:03
【问题描述】:

我必须确定是否给定一个表示树的列表,该树是否是有效的 BST(这个问题来自 leetcode)。我看过其他关于此的帖子,但我想知道是否有人可以帮助我采用我的方法,因为这显然是不对的。例如,对于树 [1,2,3],其中 1 是根,2 是左孩子,3 是右孩子,我的代码返回 true。希望它只需要很小的更改,但可能是整个函数的方法不正确。

这是我的代码:

def isValidBST(self, root):
    if (root == None):
        return True
    if (root.left == None or root.left.val < root.val):
        return self.isValidBST(root.left)
    if (root.right == None or root.right.val > root.val):
        return self.isValidBST(root.right)
    return False

其次,我见过带有一个辅助函数的方法,它接受一个最小值/最大值,但这让我感到困惑。如果有人也想解释为什么这种方法是一个好的/更好的方法,那将不胜感激!

【问题讨论】:

  • 如果.. or root.left).val &lt; root.val是假的,你不应该立即返回False吗? (对于right,同样——倒置。)
  • 我看不出你在哪里有“代表树的列表”
  • None比较时使用is Nonestackoverflow.com/questions/3257919/…
  • 我认为你必须实现min()max()。考虑一棵树:root.val=2root.left.val=1root.left.right.val=3,所有其他节点都设置为None。那个无效的 BST 会通过你的算法,不是吗?
  • @Robᵩ:我喜欢你是如何捕捉到这一点的,到目前为止 3 个回答者(包括我)都没有 :)

标签: python recursion binary-search-tree


【解决方案1】:

我会为Nodes 创建一个min_max 方法,它可以找到以Node 为根的树的最小值和最大值。在找到这些时进行完整性检查,然后isValidBST 可以捕获异常

def max_min(self): 

    '''
    Returns maximum and minimum values of the keys of the tree rooted at self. 
    Throws an exception if the results are not correct for a BST
    '''

    l_max, l_min = self.left.max_min() if self.left else (self.val, self.val)
    if l_max > self.val:
        raise ValueError('Not a BST')
    r_max, r_min = self.right.max_min() if self.right else (self.val, self.val)
    if r_min < self.val:
        raise ValueError('Not a BST')
    return l_min, r_max

def isValidBST(self):
    try:
        if self.max_min():
            return True
    except ValueError:
            return False

【讨论】:

  • 非常感谢!我真的很感激!
【解决方案2】:

这是一种实现有效性检查的方法:

class BST:

    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def isValidBST(self):
        '''
        Simultaneously check for validity and set our own min and max values.
        '''
        self.min = self.max = self.value
        if self.left:
            if not self.left.isValidBST():
                return False
            if self.left.max >= self.value:
                return False
            self.min = self.left.min
        if self.right:
            if not self.right.isValidBST():
                return False
            if self.right.min < self.value:
                return False
            self.max = self.right.max
        return True

assert BST(2, BST(1), BST(3)).isValidBST()
case = BST(2, BST(1, None, BST(3)))
assert case.left.isValidBST()
assert not case.isValidBST()

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多