码迷,mamicode.com
首页 > 编程语言 > 详细

遍历二叉树 python

时间:2019-02-26 15:27:25      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:pre   return   bcd   nod   class   node   end   utf-8   coding   

#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

标签:pre   return   bcd   nod   class   node   end   utf-8   coding   

原文地址:https://www.cnblogs.com/sjxm2017/p/10437157.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!