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

时间:2023-03-09 20:48:26
python二叉树递归算法之后序遍历,前序遍历,中序遍历
 #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-11-18 08:53:45
# @Author : why_not_try
# @Link : http://example.org
# @Version : python 2.7 class Tree(object):
def __init__(self,data,left,right):
self.data=data
self.left=left
self.right=right
def post_visit(Tree):
if Tree:
post_visit(Tree.left)
post_visit(Tree.right)
print Tree.data
def pre_visit(Tree):
if Tree:
print Tree.data
pre_visit(Tree.left)
pre_visit(Tree.right)
def in_visit(Tree):
if Tree:
in_visit(Tree.left)
print Tree.data
in_visit(Tree.right)
node1=Tree(1,0,0)
node2=Tree(2,0,0)
node3=Tree(3,node1,node2)
node4=Tree(4,0,0)
node5=Tree(5,node4,node3) print "the post_visit is ....."
post_visit(node5) print "the pre_visit is......."
pre_visit(node5) print "the in_visit is ......."
in_visit(node5)

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

此为node5:

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

运行结果如下:

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