前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python二叉树递归算法之后序遍历,前序遍历,中序遍历

python二叉树递归算法之后序遍历,前序遍历,中序遍历

作者头像
用户1149564
发布2018-01-11 18:02:47
9610
发布2018-01-11 18:02:47
举报
文章被收录于专栏:Micro_awake webMicro_awake web
代码语言:javascript
复制
 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Date    : 2016-11-18 08:53:45
 4 # @Author  : why_not_try
 5 # @Link    : http://example.org
 6 # @Version : python 2.7
 7 
 8 class Tree(object):
 9     def __init__(self,data,left,right):
10         self.data=data
11         self.left=left
12         self.right=right
13 def post_visit(Tree):
14     if Tree:
15         post_visit(Tree.left)
16         post_visit(Tree.right)
17         print Tree.data
18 def pre_visit(Tree):
19     if Tree:
20         print Tree.data
21         pre_visit(Tree.left)
22         pre_visit(Tree.right)
23 def in_visit(Tree):
24     if Tree:
25         in_visit(Tree.left)
26         print Tree.data
27         in_visit(Tree.right)
28 node1=Tree(1,0,0)
29 node2=Tree(2,0,0)
30 node3=Tree(3,node1,node2)
31 node4=Tree(4,0,0)
32 node5=Tree(5,node4,node3)
33 
34 print "the post_visit is ....."
35 post_visit(node5)
36 
37 print "the pre_visit is......."
38 pre_visit(node5)
39 
40 print "the in_visit is ......."
41 in_visit(node5)

代码很简单,相信一看大部分就能理解。在每一个遍历算法中首先if Tree 为了防止树的左节点或右节点为空时(0代表为空)还去遍历 ,此时程序运行将会报错。

此为node5:

运行结果如下:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-11-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档