题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
该题目是根据前序遍历和中序遍历重建二叉树,这里可以利用递归的方法实现。
前序遍历序列{1,2,4,7,3,5,6,8},是从整棵树的头节点开始遍历,所以该序列的第一个节点1就是树的根节点。再来看中序遍历序列{4,7,2,1,5,3,8,6},找到头节点1在本序列中的位置,发现头节点1之前有3个数字(4、7、2,这里就是左子树的节点),后面有4个节点数(5、3、8、6,这里是右子树的节点);确定好根节点和左、右子树的节点划分之后,再进一步去构建左、右子树,在左子树划分节点前序遍历序列中,2、4、7中2明显为根节点,而在中序的遍历序列4、7、2,明显看出,4和7在2的左子树;再看右子树划分节点前序遍历序列,3、5、6、8中3明显为根节点,在中序遍历序列中为5、3、8、6,则5为其左子树节点的划分,8和6为其右子树节点的划分。以此类推下去。可以用递归实现。
# -*- coding: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):
# write code here
if not pre or not tin:
return None
index = tin.index(pre[0])
inorder_left = tin[0:index]
inorder_right = tin[index+1:]
root = TreeNode(pre[0])
preorder_left = pre[1:len(inorder_left)+1]
preorder_right = pre[-len(inorder_right):]
root.left = self.reConstructBinaryTree(preorder_left,inorder_left)
root.right = self.reConstructBinaryTree(preorder_right,inorder_right)
return root
判断前序遍历和中序遍历是否为空这个操作必不可少。
延伸:
根据中序遍历序列{7,3,8,1,9,4,0,5,2,6}和后序遍历序列{7,8,3,9,4,1,5,6,2,0},生成二叉树,然后输出前序遍历序列。
class Solution:
def __init__(self):
self.arr = []
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, tin, post):
# write code here
if not tin or not post:
return None
index = tin.index(post[-1])
inorder_left = tin[0:index]
inorder_right = tin[index+1:]
root = TreeNode(post[-1])
step = len(post)-len(inorder_right) -1
postorder_left = post[0:step]
postrder_right = post[-(len(inorder_right)+1):-1]
root.left = self.reConstructBinaryTree(inorder_left,postorder_left)
root.right = self.reConstructBinaryTree(inorder_right,postrder_right)
self.arr.append(root)
return root
# 前序遍历
def preorder_traversal(self,root):
# 这一句很关键,是递归停止的条件
if root == None:
return
print(root.val)
self.preorder_traversal(root.left)
self.preorder_traversal(root.right)
验证:
if __name__ == '__main__':
l1 = list([7,3,8,1,9,4,0,5,2,6])
l2 = list([7,8,3,9,4,1,5,6,2,0])
s = Solution()
s.reConstructBinaryTree(l1,l2)
s.preorder_traversal(s.arr[-1])
如有错误之处,请指正。