标签:广度 coding pop __name__ self child main item nbsp
# encoding=utf-8 class Node(object): def __init__(self, item): self.item = item self.lchild = None self.rchild = None class BinaryTree(object): def __init__(self, node=None): self.root = node def add(self, item): """添加节点""" if self.root is None: self.root = Node(item) else: # 使用队列来处理使用广度优先查找要添加元素的位置 queue = [] queue.append(self.root) while len(queue) > 0: node = queue.pop(0) if node.lchild is not None: queue.append(node.lchild) else: node.lchild = Node(item) return if node.rchild is not None: queue.append(node.rchild) else: node.rchild = Node(item) return def breadth_travel(self): """广度优先遍历二叉树""" if self.root is None: return else: queue = [] queue.append(self.root) while len(queue) > 0: node = queue.pop(0) print(node.item, end=" ") if node.lchild: queue.append(node.lchild) if node.rchild: queue.append(node.rchild) # ============================================ # 深度优先3种遍历二叉树方式 def preorder_travel(self, node): """先序遍历 即 根 左 右""" if node: print(node.item, end=" ") self.preorder_travel(node.lchild) self.preorder_travel(node.rchild) else: return def inorder_travel(self, node): """中序遍历 即 左 根 右""" if node: self.inorder_travel(node.lchild) print(node.item, end=‘ ‘) self.inorder_travel(node.rchild) else: return def postorder_travel(self, node): """后序遍历 即 左 右 根""" if node: self.postorder_travel(node.lchild) self.postorder_travel(node.rchild) print(node.item, end=‘ ‘) else: return if __name__ == ‘__main__‘: t = BinaryTree() t.add(0) t.add(1) t.add(2) t.add(3) t.add(4) t.add(5) t.add(6) t.add(7) t.add(8) t.add(9) t.breadth_travel() print("") t.preorder_travel(t.root) print("") t.inorder_travel(t.root) print("") t.postorder_travel(t.root) print("")
标签:广度 coding pop __name__ self child main item nbsp
原文地址:http://www.cnblogs.com/wgDream/p/7535796.html