遍历二叉树 python
Posted sjxm2017
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了遍历二叉树 python相关的知识,希望对你有一定的参考价值。
#coding=UTF-8
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 None
print root.value
preTraverse(root.left)
preTraverse(root.right)
#中序遍历
def midTraverse(root):
if root ==None:
return None
midTraverse(root.left)
print root.value
midTraverse(root.right)
#后序遍历
def afterTraverse(root):
if root ==None:
return None
afterTraverse(root.left)
afterTraverse(root.right)
print root.value
#如果知道二叉树的前序遍历和中序遍历,求这棵二叉树的后序遍历
def findTree(preList,midList,afterList):
if len(preList)==0:
return
if len(preList)==1:
afterList.append(preList[0])
return
root=preList[0]
n=midList.index(root)
findTree(preList[1:n+1],midList[:n],afterList)
findTree(preList[n + 1:], midList[n + 1:], afterList)
afterList.append(root)
return afterList
if __name__==‘__main__‘:
root = Node(‘D‘,Node(‘B‘,Node(‘A‘),Node(‘C‘)),Node(‘E‘,right=Node(‘G‘,Node(‘F‘))))
print ‘前序遍历‘
preTraverse(root)
print ‘中序遍历‘
midTraverse(root)
print ‘后序遍历‘
afterTraverse(root)
preList = list(‘DBACEGF‘)
midList = list(‘ABCDEFG‘)
afterList = []
print findTree(preList,midList,afterList)
以上是关于遍历二叉树 python的主要内容,如果未能解决你的问题,请参考以下文章