# coding:utf8 class Node(): def __init__(self, _item): self.item = _item self.left = None self.right = None class Tree(): def __init__(self): self.root = None def append(self, _item): node = Node(_item) cur = self.root point_list = [cur] # 如果添加的是根节点 if cur == None: self.root = node return while True: target_point = point_list.pop(0) if target_point.left == None: target_point.left = node return else: point_list.append(target_point.left) if target_point.right == None: target_point.right = node return else: point_list.append(target_point.right) # 广度优先搜索遍历 def travel(self): cur = self.root point_list = [cur] while point_list: target_point = point_list.pop(0) print(target_point.item) if target_point.left: point_list.append(target_point.left) if target_point.right: point_list.append(target_point.right) # 深度优先搜索遍历 def forward(self, root): # 前序遍历 :根左右 if root == None: return print(root.item) self.forward(root.left) self.forward(root.right) def middle(self, root): # 中序遍历 :左根右 if root == None: return self.middle(root.left) print(root.item) self.middle(root.right) def back(self, root): # 后序遍历 :左右根 if root == None: return self.back(root.left) self.back(root.right) print(root.item) if __name__ == "__main__": tree = Tree() tree.append(1) tree.append(2) tree.append(3) tree.append(4) tree.append(5) tree.append(6) tree.append(7) # tree.travel() # tree.forward(tree.root) # tree.middle(tree.root) tree.back(tree.root)