如何从python中的二进制搜索树中查找值?

时间:2018-12-02 06:09:39

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

我想创建一个交互式二进制搜索树(BST)。因此,我使用以下代码创建了BST

class BTreeNode(object):
  def __init__(self, data):
    self.data = data
    self.rChild = None
    self.lChild = None

  def __str__(self):
    return (self.lChild.__str__() + '<-' if self.lChild != None 
    else '') + self.data.__str__() + (
    '->' + self.rChild.__str__() if self.rChild != None else '')

  # Insert method to create nodes
  def insert(self, btreeNode):
    if self.data > btreeNode.data:  # insert left
        if self.lChild == None:
            self.lChild = btreeNode
        else:
            self.lChild.insert(btreeNode)
    else:  # insert right
        if self.rChild == None:
            self.rChild = btreeNode
        else:
            self.rChild.insert(btreeNode)
  # Insert method to create nodes

  # findval method to compare the value with nodes
  def findval(self, lkpval):
    if lkpval < self.data:
        if self.lChild.data is None:
            return str(lkpval)+" Not Found"
        return self.lChild.findval(lkpval)
    elif lkpval > self.data:
        if self.rChild.data is None:
            return str(lkpval)+" Not Found"
        return self.rChild.findval(lkpval)
    else:
        print(str(self.data) + ' is found')
  # findval method to compare the value with nodes

def display():
 btreeRoot = BTreeNode(5)
 print('inserted %s:' % 5, btreeRoot)

 btreeRoot.insert(BTreeNode(7))
 print('inserted %s:' % 7, btreeRoot)

 btreeRoot.insert(BTreeNode(3))
 print('inserted %s:' % 3, btreeRoot)

 btreeRoot.insert(BTreeNode(1))
 print('inserted %s:' % 1, btreeRoot)

 # print(btreeRoot.findval(3))

print(display())

如果执行上述代码,我将获得以下交互式输出为

  

插入5:5

     

插入7:5-> 7

     

插入3:3 <-5-> 7

     

已插入1:1 1 <-3 <-5-> 7

这是我的预期输出,我明白了。另外,我想从BST中找到一个值。所以我在显示功能中使用了以下代码作为

# print(btreeRoot.findval(3))

如果我取消注释代码,则会出错。因此,如何修改我的代码以显示BST中是否存在3?谢谢。

1 个答案:

答案 0 :(得分:1)

执行检查"default_icon":fs.write时会发生问题。这些行应分别用if self.lChild.data is Noneif self.rChild.data is None替换,因为您的班级暗示那些属性是if self.lChild is None的属性,而不是它们的if self.rChild is None属性。

也可以考虑使用None代替data。在这种情况下,这不是什么大问题,但在其他情况下可能会引起麻烦。请在此处查看详细信息:Python None comparison: should I use "is" or ==?

相关问题