''' 链表思想 构造二叉树 ''' class Node(object): """""" def __init__(self, item): self.elem = item self.lchild = None self.rchild = None class Tree(object): """二叉树""" def __init__(self): self.root = None def add(self, item): node = Node(item) if self.root is None: self.root = node #直接让根节点指向该node return queue = [self.root] #根节点入队 while queue: #只要列表不为空,则进入循环,否则结束。 注意:bool( []) --> False ,but, bool( [None] )--> True 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 breadth_travel(self): """广度遍历""" if self.root is None: return 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) ''' 每次都看成一棵树 前序遍历的递推公式: 根左右 preOrder(r) = print r->preOrder(r->left)->preOrder(r->right) 中序遍历的递推公式: 左根右 inOrder(r) = inOrder(r->left)->print r->inOrder(r->right) 后序遍历的递推公式: 左右根 postOrder(r) = postOrder(r->left)->postOrder(r->right)->print r 时间复杂度:3种遍历方式中,每个节点最多会被访问2次,所以时间复杂度是O(n)。 ''' def preorder(self, r): """先序遍历""" if r is None: #终止节点 return print(r.elem, end=" ") self.preorder(r.lchild) self.preorder(r.rchild) def inorder(self, r): """中序遍历""" if r is None: return self.inorder(r.lchild) print(r.elem, end=" ") self.inorder(r.rchild) def postorder(self, node): """后序遍历""" if node is None: return self.postorder(node.lchild) self.postorder(node.rchild) print(node.elem, end=" ") if __name__ == "__main__": tree = 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.breadth_travel() print(" ") tree.preorder(tree.root) print(" ") tree.inorder(tree.root) print(" ") tree.postorder(tree.root) print(" ")
03_【数据结构】07_ Python实现 构造二叉树 层次遍历 先序遍历 中序遍历 后序遍历
最新推荐文章于 2023-10-12 00:33:33 发布