Breadth-first traversal order is: 50,20,60,15,30,70.
In the code, we use a breadth-first traversal of the queue, the root node first in the queue, using a FIFO queue, the queue access node extracted, and are left child node and the right child node queues the cycle continue until the queue is empty.
# encoding=utf-8
from queue import Queue
class TreeNode(object):
def __init__(self,var,left=None,right=None):
self.var = var
self.left = left
self.right = right
class BinaryTree(object):
def __init__(self,root = None):
self.root = root
def breathSearth(self):
if self.root == None:#判断一下二叉树是否为空
return None
retList = [] #存遍历二叉树时候的结果
queue = Queue() #声明一个队列
queue.put(self.root) #把根节点放到队列中,开始遍历
while queue.empty() is not True:
#只要队列有节点,就会一直执行
node = queue.get()#实例化node,将二叉树实例化给node
retList.append(node.var)
if node.left != None:
queue.put(node.left)
if node.right != None:
queue.put(node.right)
return retList
if __name__ == '__main__':
rootNode = TreeNode(50)
rootNode.left = TreeNode(20,left=TreeNode(15),right=TreeNode(30))
rootNode.right = TreeNode(60,right=TreeNode(70))
#以上是构造二叉树实例,这里完成了二叉树的构造,才能有node=queue.get()的实例化
tree = BinaryTree(rootNode)#把上面刚刚创建的整个二叉树都给了BinaryTree
retList = tree.breathSearth()
print (retList)