#二叉树结点
class BinaryTreeNode(object):
def __init__(self):
self.data='#'
self.LeftChild=None
self.RightChild=None
#二叉树类,创建二叉树和遍历二叉树
class BinaryTree(object):
def CreateBinaryTree(self,Root):
data=input('->')
if data=='#':
Root=None
else:
Root.data=data
Root.LeftChild=BinaryTreeNode()
self.CreateBinaryTree(Root.LeftChild)
Root.RightChild=BinaryTreeNode()
self.CreateBinaryTree(Root.RightChild)
def PreOrder(self,Root):
if Root is not None:
self.VisitBinaryTreeNode(Root)
self.PreOrder(Root.LeftChild)
self.PreOrder(Root.RightChild)
def InOrder(self,Root):
if Root is not None:
self.InOrder(Root.LeftChild)
self.VisitBinaryTreeNode(Root)
self.InOrder(Root.RightChild)
def PostOrder(self,Root):
if Root is not None:
self.PostOrder(Root.LeftChild)
self.PostOrder(Root.RightChild)
self.VisitBinaryTreeNode(Root)
def VisitBinaryTreeNode(self,BinaryTreeNode):
if BinaryTreeNode.data is not '#':
print(BinaryTreeNode.data)
########################
#主程序
########################
bTN = BinaryTreeNode()
bT = BinaryTree()
print ('创建一棵二叉树\n')
print (' 4')
print (' / \\')
print (' 5 6')
print (' / \\ \\')
print (' 1 2 7 ')
print ('4 5 1 # # 2 # # 6 # 7 # #')
#创建一棵二叉树
print('请仿照上述序列,输入某一二叉树中各结点的值(#表示空结点),每输入一个值按回车换行:')
bT.CreateBinaryTree(bTN)
print ('对二叉树进行前序遍历:\n')
#前序遍历二叉树
bT.PreOrder(bTN)
print ('对二叉树进行中序遍历:\n')
#中序遍历二叉树
bT.InOrder(bTN)
print ('对二叉树进行后序遍历:\n')
#后序遍历二叉树
bT.PostOrder(bTN)
来源:CSDN
作者:tianrandai12
链接:https://blog.csdn.net/tianrandai12/article/details/104228953