问题描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
原因分析:
- pre[0]是root,在in中找到root的位置
- 找到root位置后,根据其index确定左右子树的pre和in的范围, 递归
解决方案:
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin:
return None
root=TreeNode(pre[0])#确定根节点,默认先序的第一个数值
k=tin.index(pre[0])#在中序中找到等于先序第一个数值的位置,等于k
root.left=self.reConstructBinaryTree(pre[1:k+1], tin[0:k])#递归遍历先序的左子树,和中序的左子树
root.right=self.reConstructBinaryTree(pre[k+1:], tin[k+1:])#递归遍历先序的右子树和中序的右子树
return root
拓展
中序和后序
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, ldr, tin):
# write code here
if not ldr or not tin:
return None
root=TreeNode(ldr[-1])#确定根节点,默认先序的第一个数值
k=tin.index(ldr[-1])#在中序中找到等于先序第一个数值的位置,等于k
root.left=self.reConstructBinaryTree(ldr[0:k+1], tin[0:k])#递归遍历先序的左子树,和中序的左子树
root.right=self.reConstructBinaryTree(ldr[k+1:-2], tin[k+1:])#递归遍历先序的右子树和中序的右子树
return root