我的二叉搜索树验证码有什么问题?

时间:2015-08-21 13:54:36

标签: python recursion data-structures binary-search-tree

根据定义,二叉树必须满足以下条件:
  1。节点的左子树仅包含键小于的节点     节点的密钥。
 2.节点的右子树仅包含键大于节点键的节点  3.左右子树​​也必须是二叉搜索树。

我的代码为输入 [10,5,15,#,#,6,20] 输入 True 但不正确,必须返回 错误
输入遵循级别顺序遍历,其中'#'表示下面没有节点的路径终结符。

这是树:

         10
        /  \
       5   15
          /  \
         6    20

这是我的代码:

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None  


    def isValidBST(self, root)
    """  
    :type root: TreeNode  
    :rtype: bool  
    """  

    if not root:  
        return True  
    else:  
        if root.left and root.right:  
            return root.left.val < root.val < root.right.val and \    
                   self.isValidBST(root.left) and self.isValidBST(root.right)  
        elif root.left and not root.right:  
            return root.left.val < root.val and self.isValidBST(root.left)  
        elif root.right and not root.left:  
            return root.right.val > root.val and self.isValidBST(root.right) 
        else:  
            return True  

2 个答案:

答案 0 :(得分:0)

考虑一个BST,其中A是根值,B是其左子树根的值,C是右子树根下的值。您的代码将验证A&gt; B,B&lt; B&lt; C.但它检查是否A&gt;下进行。

或者,从您的示例:它检查5 <10,10 <15,6 <15和15 <20,但检查6> 10。

回想一下,BST的定义是关于子树中的所有节点,而不仅仅是根。

答案 1 :(得分:0)

您的算法没有正确实现第二个条件。您应该将根值与左子树的最大值和右子树的最小值进行比较。

或者,您可以对树进行顺序遍历,该遍历应该在二叉搜索树中按升序排列。