Python实现二叉树的遍历
2018年12月11日 13:34
1.二叉树的三种基本遍历(先序遍历,中序遍历,后序遍历)
class Node:
def __init__(self,value=None,left=None,right=None):
self.value = value
self.left = left
self.right = right
def preTraverse(root):
"""先序遍历"""
if root == None:
return
print(root.value, end='')
preTraverse(root.left)
preTraverse(root.right)
def midTraverse(root):
"""中序遍历"""
if root == None:
return
midTraverse(root.left)
print(root.value, end='')
midTraverse(root.right)
def afterTraverse(root):
"""后序遍历"""
if root == None:
return
afterTraverse(root.left)
afterTraverse(root.right)
print(root.value, end='')
if __name__ == '__main__':
root = Node('D',Node('B',Node('A'),Node('C')),Node('E',right=Node('G',Node('F'))))
print('preTraverse:' ,end='')
preTraverse(root)
print('')
print('midTraverse:' ,end='')
midTraverse(root)
print('')
print('afterTraverse:' ,end='')
afterTraverse(root)
"""
打印答案:
preTraverse:DBACEGF
midTraverse:ABCDEFG
afterTraverse:ACBFGED
"""
2.已知先序遍历和中序遍历求后序遍历,和已知中序遍历和后序遍历求先序遍历
class Node:
def __init__(self,vaule=None,left=None,right=None):
self.vaule = vaule
self.left = left
self.right = right
def get_afterTraverse(preTraverse,midTraverse,afterTraverse):
"""
已知先序遍历和中序遍历求后序遍历
"""
if len(preTraverse) == 0:
return
if len(preTraverse) == 1:
afterTraverse.append(preTraverse[0])
return
root = preTraverse[0]
n = midTraverse.index(root)
get_afterTraverse(preTraverse[1:n+1],midTraverse[:n],afterTraverse)
get_afterTraverse(preTraverse[n+1:],midTraverse[n+1:],afterTraverse)
afterTraverse.append(root)
def get_preTraverse(preTraverse,midTraverse,afterTraverse):
"""
已知中序遍历和后序遍历求先序遍历
"""
if len(afterTraverse) == 0:
return
if len(afterTraverse) == 1:
preTraverse.append(afterTraverse[0])
return
root = afterTraverse[-1]
preTraverse.append(root)
n = midTraverse.index(root)
get_preTraverse(preTraverse,midTraverse[:n],afterTraverse[:n])
get_preTraverse(preTraverse,midTraverse[n+1:],afterTraverse[n:-1])
if __name__ == '__main__':
preTraverse = ['G','D','A','F','E','M','H','Z']
midTraverse = ['A','D','E','F','G','H','M','Z']
afterTraverse = ['A','E','F','D','H','Z','M','G']
print('求后序遍历:')
afterlist = []
get_afterTraverse(preTraverse,midTraverse,afterlist)
print(afterlist)
print('求先序遍历:')
prelist = []
get_preTraverse(prelist,midTraverse,afterTraverse)
print(prelist)
"""
输出答案:
求后序遍历:
['A', 'E', 'F', 'D', 'H', 'Z', 'M', 'G']
求先序遍历:
['G', 'D', 'A', 'F', 'E', 'M', 'H', 'Z']
"""
作者: ming.zhong
阅读: 977
评论: 0
点赞
收藏
关注
本文版权归作者和此站共有,欢迎转载,但未经作者同意必须声明引用出处,且在文章页面明显位置给出原文连接。
评论
Nickname
Comment
Submit
Cancel
暂时还没有评论,欢迎评论!