二叉树的广度优先遍历、深度优先遍历

from queue import Queue

"""
二叉树: 1.深度遍历 2.广度遍历 """ class Node(object): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right class BinaryTree(object): def __init__(self, root=None): self.root = root def pre_ord(self, result=[], node='root'): """先序遍历""" if node == 'root': node = self.root if node is not None: result.append(node.value) if node.left: self.pre_ord(result, node.left) if node.right: self.pre_ord(result, node.right) return result def in_order(self, result=[], node='root'): """中序遍历""" if node == 'root': node = self.root if node is not None: if node.left: self.in_order(result, node.left) result.append(node.value) if node.right: self.in_order(result, node.right) return result def post_order(self, result=[], node='root'): """后序遍历""" if node == 'root': node = self.root if node is not None: if node.left: self.post_order(result, node.left) if node.right: self.post_order(result, node.right) result.append(node.value) return result def breathSearch(self): """广度优先遍历""" if self.root is None: return None resultList = [] q = Queue() q.put(self.root) while not q.empty(): node = q.get() resultList.append(node.value) if node.left: q.put(node.left) if node.right: q.put(node.right) return resultList if __name__ == '__main__': # 构造二叉树的结点 rootNode = Node(50) rootNode.left = Node(20, left=Node(15), right=Node(30)) rootNode.right = Node(60, right=Node(70)) bt = BinaryTree(rootNode) # 构造二叉树 print(bt.pre_ord()) print(bt.in_order()) print(bt.post_order()) print(bt.breathSearch())

 

posted @ 2019-08-06 11:46  reyinever  阅读(654)  评论(0编辑  收藏  举报