class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#1.由中序和前序重建二叉树,输出后序
#中:GDHBEAFC 前:ABDGHECF
def recreateTree(preorder,inorder):
if len(preorder)<=0:
return None
else:
root=TreeNode(preorder.pop(0))
root_index=inorder.index(root.val)
root.left=recreateTree(preorder[:root_index],inorder[:root_index])
root.right=recreateTree(preorder[root_index:],inorder[root_index+1:])
return root
def postorder(root):
global res
if root==None:
return []
else:
postorder(root.left)
postorder(root.right)
res.append(root.val)
preorder='A B D G H E C F'.split(' ')
inorder='G D H B E A F C'.split(' ')
t=recreateTree(preorder,inorder)
res=[]
postorder(t)
print(','.join(str(i) for i in res))
#2.由中序和后序重建二叉树,输出前序
#中:GDHBEAFC 前:ABDGHECF 后:GHDEBFCA
def recreateTree(postorder,inorder):
if len(postorder)<=0:
return None
else:
root=TreeNode(postorder.pop(-1))
root_index=inorder.index(root.val)
root.left=recreateTree(postorder[:root_index],inorder[:root_index])
root.right=recreateTree(postorder[root_index:],inorder[root_index+1:])
return root
def preorder(root):
global res
if root==None:
return []
else:
res.append(root.val)
preorder(root.left)
preorder(root.right)
postorder='G H D E B F C A'.split(' ')
inorder='G D H B E A F C'.split(' ')
t=recreateTree(postorder,inorder)
res=[]
preorder(t)
print(','.join(str(i) for i in res))
#3.已知前序和后序,不能重建二叉树,因为前序和后序不知道树的左右关系;
#由前序和后序,可以有几种中序的输出方法?
重建二叉树和遍历二叉树
最新推荐文章于 2021-09-19 22:24:54 发布