前序+中序,中序+后序均可以构造出原本的树结构;前序加后序无法构造唯一的树结构。
假设节点是这样的:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
假设树是这样的:
root=TreeNode(1)
root_1_1=TreeNode(2)
root_1_2=TreeNode(3)
root_1_1_1=TreeNode(4)
root_1_1_2=TreeNode(5)
root_1_2_1=TreeNode(6)
root.left=root_1_1
root.right=root_1_2
root_1_1.left=root_1_1_1
root_1_1.right=root_1_1_2
root_1_2.left=root_1_2_1
那么,现在写出前序和中序表达,使用以下函数,能得出正确的树结构;之后用后序的方式打印:
pre=[1,2,4,5,3,6]
post=[4,2,5,1,6,3]
root_pre_tin = s.reConstructBinaryTree_pre_tin(pre,post)
my_print_post(root_pre_tin)
桶同理,现在写出中序和后序表达,使用以下函数,能得出正确的树结构;之后用前序的方式打印:
tin=[4,2,5,1,6,3]
post=[4,5,2,6,3,1]
root_tin_post = s.reConstructBinaryTree_tin_post(tin,post,0,len(tin)-1,0,len(post)-1)
my_print_pre(root_tin_post)
sollution类定义如下:
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree_pre_tin(self, pre, tin):
# write code here
if not pre or not tin:
return None
else:
root=TreeNode(pre.pop(0))
index=tin.index(root.val)
# print("root",root.val)
# print("left",pre,tin[0:index])
# print("right",pre,tin[1+index:])
root.left=self.reConstructBinaryTree_pre_tin(pre,tin[0:index])
root.right=self.reConstructBinaryTree_pre_tin(pre,tin[index+1:])
return root
def reConstructBinaryTree_tin_post(self, tin,post,tin_s,tin_end,post_s,post_e):
# write code here
root = TreeNode(post[post_e])
if post_s==post_e:
return root
index=tin.index(root.val)
if index-1>=tin_s:
root.left=self.reConstructBinaryTree_tin_post(tin,post,tin_s,index-1,post_s,post_s+index-1-tin_s)
if index+1<=tin_end:
root.right=self.reConstructBinaryTree_tin_post(tin,post,index+1,tin_end,post_s+index-tin_s,post_e-1)
return root
自定义打印方式如下:
def my_print_pre(root):
if root:
print("当前节点:",root.val)
if root.left:
print(root.val,"的左节点")
my_print_pre(root.left)
if root.right:
print(root.val,"的右节点")
my_print_pre(root.right)
def my_print_post(root):
if root.left:
my_print_post(root.left)
if root.right:
my_print_post(root.right)
if root:
print(root.val)