标签:元素 tree 特殊情况 item none class __init__ nbsp col
# 树的单个结点 class Node: def __init__(self,elem): # 结点数据 self.elem = elem # 左子树和右子树 self.lchild = None self.rchild = None # 二叉树的实现 class my_tree: # 初始化空树 def __init__(self): self.root = None # 树添加元素,广度遍历 + 队列 def add(self,item): # 创建新结点 node = Node(item) # 特殊情况 if self.root is None: self.root = node return else: # 队列的方式实现,队列最开始存根 queue = [self.root] # 循环处理队列,直到将新结点添加进树为止 while queue: # 取出第一个未处理的结点 cur_node = queue.pop(0) # 判断取出的结点有没有左或右 # 左结点是空,则添加新结点 if cur_node.lchild is None: cur_node.lchild = node return else: # 左结点不是空,则将左结点添加进队列 queue.append(cur_node.lchild) if cur_node.rchild is None: cur_node.rchild = node return else: queue.append((cur_node.rchild)) # 广度遍历 # 广度遍历 def tree_travle(self): if self.root is None: return else: # 队列先存根结点 queue = [self.root] while queue: # 取第一个未处理的结点 cur_node = queue.pop(0) print(cur_node.elem, end=‘ ‘) if cur_node.lchild is not None: queue.append(cur_node.lchild) if cur_node.rchild is not None: queue.append(cur_node.rchild) # 深度遍历 # 深度遍历 # 先序 根左右 def xian(self, root): if root == None: return else: print(root.elem, end=‘ ‘) # 递归 self.xian(root.lchild) self.xian(root.rchild) # 中序 左根右 def zhong(self,root): if root == None: return else: self.zhong(root.lchild) print(root.elem,end=‘ ‘) self.zhong(root.rchild) # 后序 左右根 def hou(self,root): if root == None: return else: self.hou(root.lchild) self.hou(root.rchild) print(root.elem,end=‘ ‘) if __name__ == ‘__main__‘: tree = my_tree() tree.add(0) tree.add(1) tree.add(2) tree.add(3) tree.add(4) tree.add(5) tree.add(6) tree.add(7) tree.add(8) tree.add(9) # 广度 tree.tree_travle() print(‘‘) # 先序 tree.xian(tree.root) print(‘‘) # 中序 tree.zhong(tree.root) print(‘‘) # 后序 tree.hou(tree.root)
标签:元素 tree 特殊情况 item none class __init__ nbsp col
原文地址:https://www.cnblogs.com/hude/p/12950468.html