Python中二进制搜索树上的广度优先搜索

时间:2018-05-18 21:47:31

标签: python queue binary-search-tree breadth-first-search

我一直致力于构建不同的数据类型并对其应用各种排序算法。我目前正在二叉搜索树上进行广度优先搜索。我的代码与您在网上随处可见的代码几乎相同,但它始终如一地打印我的价值两次,而我现在的心情令人难以置信。非常感谢任何指导。

# Remove (dequeue) function for Queue class
def remove(self, current=''):
    if current == '':
        current = self.tail
    # start looping/recurring to find the front of the queue
    if current.next:
        if current.next.next:
            current = current.next
            return self.remove(current)
            # side note - I'm doubting the usefulness of recursion here
        else:
            n = current.next.value
            current.next = None
            self.size -= 1
            return n
    elif current == self.tail:
        if current.value:
            n = current.value
            current = None
            self.size -= 1
            # print("Queue is now empty - returning final number")
            return n
        else:
            return "Queue is already empty."
    else:
        raise ValueError("mind boggling error...") #never raised

# Add (enqueue) function for my queue:
def add(self,value):
    n = Node(value) # create the new node we're adding
    n.next = self.tail # point the new node to link to the old tail
    self.tail = n # now have the tail point to the new node
    self.size += 1


# Breadth First Search function for the Binary Search Tree
def bfs(self):
    """
    This is currently VERY inefficient from a memory
    standpoint, as it adds a subtree for EACH node...right?
    or is it just the names/addresses of the objects being stored in
    each node, and each node is still only in the same memory location?
    """
    queue = Queue()
    queue.add(self)
    while queue.size > 0:
        current = queue.remove()
        print(current.value)

        if current.left_child:
            queue.add(current.left_child)
        if current.right_child:
            queue.add(current.right_child)

# how I typically test:
bst = BinarySearchTree(50)
for i in range(1,10):
    bst.insert_node(i*4)
bst.bfs()

示例输出: 25 25 4 28 4 28 8 32 8 32 12 36 12 36 16 16 20 20 24

看到它自己打印根节点两次,然后两个子节点一对一地,一个接一个,表明它的工作意义是逐级进入正确的顺序,但是它将左右两个孩子一起打印,直到它没有,因为可以看到它最后开始两次背对背开始打印而不是成对,并且在第二次打印24之前它会被切断。 / p>

我还应该做出免责声明,我对在队列函数中使用python列表没兴趣。本练习的重点是手动构建我的数据结构,无需使用超出整数/字符串的预构建数据。

我的GitHub上可以在https://github.com/GhostlyMowgli/data_structures_plus

找到完整的文件

再一次,这里的任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

您的问题出在queue.remove功能中,下面是违规行上有标记的固定代码(219)

  def remove(self, current=''):
    if current == '': 
        current = self.tail
    if current.next:
        if current.next.next:
            current = current.next
            return self.remove(current) # recursive - keep going to front
        else:
            n = current.next.value
            current.next = None
            self.size -= 1
            return n
    elif current == self.tail:
        # now I'm wondering if this is even smart
        # shouldn't I be checking if current is a None type?!?!
        if current.value:
            n = current.value
            self.tail = None # HERE!!!! NOT current = None
            self.size -= 1
            # print("Queue is now empty - returning final number")
            return n
        else:
            return "Queue is already empty."
    else:
        raise ValueError("mind boggling coding error...")