python算法-二叉樹廣度優先遍歷


廣度優先遍歷:優先遍歷兄弟節點,再遍歷子節點

算法:通過隊列實現--》先進先出

廣度優先遍歷的結果: 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()

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com