使用前序中序求后序遍历
# encoding: utf-8
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
if len(pre)==0:
return None
root=TreeNode(pre[0])
TinIndex=tin.index(pre[0])
root.left=self.reConstructBinaryTree(pre[1:TinIndex+1], tin[0:TinIndex])
root.right=self.reConstructBinaryTree(pre[TinIndex+1:], tin[TinIndex+1:])
return root
def PostTraversal(self,root): #后序遍历
if root != None:
self.PostTraversal(root.left)
self.PostTraversal(root.right)
print(root.val)
pre=[1,2,4,7,3,5,6,8]
tin=[4,7,2,1,5,3,8,6]
S=Solution()
root=S.reConstructBinaryTree(pre,tin)
S.PostTraversal(root)
根据上述代码修改–使用中序后序求前序遍历
class TreeNode:
def __init__(self,x):
self.val=x
self.left=None
self.right=None
class Solution:
def reConstructBinaryTree(self,post,tin):
if len(post)==0:
return None
root=TreeNode(post[-1])
TinIndex=tin.index(post[-1])
root.left=self.reConstructBinaryTree(post[0:TinIndex],tin[0:TinIndex])
root.right=self.reConstructBinaryTree(post[TinIndex:len(post)-1],tin[TinIndex+1:])
return root
def PreTraversal(self,root):
if root !=None:
print(root.val)
self.PreTraversal(root.left)
self.PreTraversal(root.right)
post =[7,4,2,5,8,6,3,1]
tin =[4,7,2,1,5,3,8,6]
pre =[1,2,4,7,3,5,6,8]
S=Solution()
root=S.reConstructBinaryTree(post,tin)
S.PreTraversal(root)