python实现二叉树的前、中、后序遍历及按层遍历
2016-02-28 22:32
656 查看
需求:
python代码实现二叉树的:1. 前序遍历,打印出遍历结果
2. 中序遍历,打印出遍历结果
3. 后序遍历,打印出遍历结果
4. 按树的level遍历,打印出遍历结果
5. 结点的下一层如果没有子节点,以‘N’代替
方法:
使用defaultdict或者namedtuple表示二叉树使用StringIO方法,遍历时写入结果,最后打印出结果
打印结点值时,如果为空,StringIO()写入‘N ’
采用递归访问子节点
代码
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # test tree as below: ''' 1 / \ / \ / \ / \ 2 3 / \ / \ / \ / \ 4 5 6 N / \ / \ / \ 7 N N N 8 9 / \ / \ / \ N N N N N N ''' from collections import namedtuple from io import StringIO #define the node structure Node = namedtuple('Node', ['data', 'left', 'right']) #initialize the tree tree = Node(1, Node(2, Node(4, Node(7, None, None), None), Node(5, None, None)), Node(3, Node(6, Node(8, None, None), Node(9, None, None)), None)) #read and write str in memory output = StringIO() #read the node and write the node's value #if node is None, substitute with 'N ' def visitor(node): if node is not None: output.write('%i ' % node.data) else: output.write('N ') #traversal the tree with different order def traversal(node, order): if node is None: visitor(node) else: op = { 'N': lambda: visitor(node), 'L': lambda: traversal(node.left, order), 'R': lambda: traversal(node.right, order), } for x in order: op[x]() #traversal the tree level by level def traversal_level_by_level(node): if node is not None: current_level = [node] while current_level: next_level = list() for n in current_level: if type(n) is str: output.write('N ') else: output.write('%i ' % n.data) if n.left is not None: next_level.append(n.left) else: next_level.append('N') if n.right is not None: next_level.append(n.right) else: next_level.append('N ') output.write('\n') current_level = next_level if __name__ == '__main__': for order in ['NLR', 'LNR', 'LRN']: if order == 'NLR': output.write('this is preorder traversal:') traversal(tree, order) output.write('\n') elif order == 'LNR': output.write('this is inorder traversal:') traversal(tree, order) output.write('\n') else: output.write('this is postorder traversal:') traversal(tree, order) output.write('\n') output.write('traversal level by level as below:'+'\n') traversal_level_by_level(tree) print(output.getvalue())
测试使用的tree截图如下:
csdn博客不能在代码注释中正确显示topo ..运行结果:
参考:
http://www.laurentluce.com/posts/binary-search-tree-library-in-python/
http://articles.leetcode.com/how-to-pretty-print-binary-tree
https://wizardforcel.gitbooks.io/liaoxuefeng/content/py3/60.html
http://stackoverflow.com/questions/13674772/printing-out-a-binary-search-tree-with-slashes
https://www.reddit.com/r/learnprogramming/comments/14681r/printing_out_a_binary_search_tree_in_level_order/
http://articles.leetcode.com/how-to-pretty-print-binary-tree/
相关文章推荐
- 第二天 Python3.4.2 函数是第一等公民 装饰器
- 第二天 Python3.4.2 函数的调用过程 生成器 yield
- Python图像处理库PIL的ImageFont模块介绍
- python学习笔记-Day6(2)
- PAT 1006. 换个格式输出整数 (15);JAVA;Python实现
- 1、提供推荐 Python代码
- 20160228python中文乱码
- Python 模块
- 最近在自学python,想以后自己搭服务器
- Windows64 系统下Python、NumPy与matplotlib 安装方法
- LeetCode:Majority Element
- [Python]time模块以及时间戳的使用
- python常用异常
- IPython使用指南
- DetectingCycles
- python(4)–yield实现异步
- Python机器学习库scikit-learn实践
- python(4)-迭代器 和 生成器
- python 调试技巧-pdb
- Python 数据库备份脚本(邮件通知+日志记录)