使用Queue在Python中进行广度优先搜索

时间:2018-08-17 04:02:04

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

有人可以帮我在python中使用bfs代码吗?它只是在打印自我价值,而不是在打印整个树。

from queue import *

class BinaryTree:
   def __init__(self,info,left,right):
    self.info  = info
    self.left  = left
    self.right = right

def bfs(self): 
    queue = Queue()
    queue.put(self)

    while not queue.empty():
        self = queue.get()
        print(self.info)

        if self.left:
            queue.put(self.left)

        if self.right:
            queue.put(self.right)
        return

nine = BinaryTree("9",None,None)
eleven = BinaryTree("11",None,None)
two = BinaryTree("2",eleven,nine)
one   = BinaryTree("1",None,None)
seven = BinaryTree("7",one,None)
five = BinaryTree("5",seven,two)
three = BinaryTree("3",None,None)
six = BinaryTree("6",None,None) 
four = BinaryTree("4",None,six)
eight = BinaryTree("8",four,three)
ten = BinaryTree("10",eight,five)

ten.bfs()

对我的回答仅仅是“ 10”,而不是整棵树。我找不到错误。

1 个答案:

答案 0 :(得分:0)

连同return语句一样,缩进也有些错误。

from queue import *

class BinaryTree:
    def __init__(self,info,left,right):
        self.info  = info
        self.left  = left
        self.right = right 

    def bfs(self): 
        queue = Queue()
        queue.put(self)

        while not queue.empty():
            self = queue.get()
            print(self.info)

            if self.left:
                queue.put(self.left)

            if self.right:
                queue.put(self.right)

nine = BinaryTree("9",None,None)
eleven = BinaryTree("11",None,None)
two = BinaryTree("2",eleven,nine)
one   = BinaryTree("1",None,None)
seven = BinaryTree("7",one,None)
five = BinaryTree("5",seven,two)
three = BinaryTree("3",None,None)
six = BinaryTree("6",None,None) 
four = BinaryTree("4",None,six)
eight = BinaryTree("8",four,three)
ten = BinaryTree("10",eight,five)

ten.bfs()

输入图:

input graph

输出:

10
8
5
4
3
7
2
6
1
11
9

参考: https://docs.python.org/3/library/queue.html#queue.Queue.get