广度优先遍历:优先遍历兄弟节点,再遍历子节点

算法:通过队列实现--》先进先出

python算法-二叉树广度优先遍历-LMLPHP

广度优先遍历的结果: 50,20,60,15,30,70,12

程序遍历这个二叉树:

# encoding=utf-8
from Queue import Queue

class TreeNode(object):
def __init__(self,val,left=None,right=None):
self.val = val
self.left = left
self.right = right

class BinaryTree(object):
def __init__(self,root=None):
self.root = root

def breathSearch(self):
retList = []
if self.root == None:
return None
queue = Queue()
queue.put(self.root)
while queue.empty() is not True:
node = queue.get()
retList.append(node.val)
if node.left != None:
queue.put(node.left)
if node.right != None:
queue.put(node.right)
return retList

if __name__ == '__main__':
root = TreeNode(50)
root.left = TreeNode(20,left=TreeNode(15),right=TreeNode(30,right=TreeNode(12)))
root.right = TreeNode(60,right=TreeNode(70))
bTree = BinaryTree(root)
print bTree.breathSearch()

05-29 01:01