利用对象的思想创建二叉树并实现四种遍历(广序,先序,中序,后序)-python3版
2017-08-10 22:36
627 查看
欢迎一起讨论学习(*^__^*) Python技术分享群: 556993881
# coding:utf-8 class Node(object): """二叉树节点""" def __init__(self, item): super(Node, self).__init__() self.item = item self.lchild = None self.rchild = None class Tree(object): """二叉树类""" def __init__(self): super(Tree, self).__init__() self.root = None def add(self, item): """添加节点""" node = Node(item) # 判断当前树是否为空 if self.root is None: self.root = node else: queue = [] queue.append(self.root) # 采用队列存放, 先将根节点放入队列中,取出,看是否有左子树和右子树,有就放入并且循环回来看子树的子树,没有则添加 while queue: temp = queue.pop(0) # 看做节点是否为空 if temp.lchild is None: temp.lchild = node break # 看右节点是否为空 elif temp.rchild is None: temp.rchild = node break # 都不为空,将左节点和右节点放入队列 else: queue.append(temp.lchild) queue.append(temp.rchild) def wide_travel(self): """广度优先遍历(广序遍历):从上到下,从左到右.利用队列""" if self.root is None: return else: queue = [] queue.append(self.root) while queue: temp = queue.pop(0) print(temp.item, end=" ") # 如果有左孩子则放入队列 if temp.lchild is not None: queue.append(temp.lchild) # 如果有右孩子则放入队列 if temp.rchild is not None: queue.append(temp.rchild) print() def preorder(self, node): """深度遍历-先序遍历(根节点-左子树-右子树)""" if node is None: return print(node.item, end=" ") self.preorder(node.lchild) self.preorder(node.rchild) def inorder(self, node): """深度遍历-中序遍历(左子树-根节点-右子树)""" if node is None: return self.inorder(node.lchild) print(node.item, end=" ") self.inorder(node.rchild) def posorder(self, node): """深度遍历-后序遍历(左子树-右子树-根节点)""" if node is None: return self.posorder(node.lchild) self.posorder(node.rchild) print(node.item, end=" ") if __name__ == '__main__': tree = Tree() for char in "ABCDEFG": tree.add(char) print("先序遍历:") tree.preorder(tree.root) print("\n中序遍历:") tree.inorder(tree.root) print("\n后序遍历:") tree.posorder(tree.root) print("\n广度遍历:") tree.wide_travel()
欢迎一起分享和交流python---->q群:556993881
相关文章推荐
- 二叉树的创建以及利用迭代实现中序、先序、后序遍历、清空
- 二叉树的四种遍历方式 (前序,中序,后序,层序遍历 python实现)
- 二叉树的创建以及利用迭代实现中序、先序、后序遍历、清空
- 采用二叉链表结构实现二叉树,并以递归遍历思想实现二叉树的创建、二叉树的遍历(先序、中序、后序和层次遍历)
- 利用前序遍历和中序遍历还原二叉树以及涉及的分治法思想
- c++实现二叉树的非递归创建以及非递归先序、中序、后序遍历
- 【python中二叉树的实现】python中二叉树的创建、三种方式递归遍历和非递归遍历
- 如何利用前序遍历序列和中序遍历序列非递归的创建二叉树
- c/c++实现利用二叉树的先序遍历和中序遍历序列重建树
- 中序二叉树、队列实现层次遍历、中序线索二叉树的创建与遍历
- 二叉树(创建、前序、中序、后序、层序遍历理论及java实现)
- python实现二叉树的建立以及遍历(递归前序、中序、后序遍历,队栈前序、中序、后序、层次遍历)
- 【数据结构与算法】(六) c 语言实现简单的二叉树静态创建及先序、中序、后序遍历
- 二叉树的创建,先序、中序、后序遍历的递归实现以及层序遍历
- 二叉树的前序,中序,后续,递归及非递归遍历的python实现
- 利用栈实现二叉树的先序,中序,后序遍历的非递归操作
- Python实现输入二叉树的先序和中序遍历,再输出后序遍历操作示例
- 二叉树的实现及四种常用遍历(python)
- 二叉树(前序,中序,后序,层序)遍历递归与循环的python实现
- 用c语言创建一颗二叉树,用递归方法实现对其进行先序、中序和后序遍历的操作。