标签: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)
标签:pre return bcd nod class node end utf-8 coding
原文地址:https://www.cnblogs.com/sjxm2017/p/10437157.html