用python要比C++简单,因为截取数组方便,且最后在索引不对时直接返回None,然后返回空恰好又是没有左子树或者说右子树的情况。
# -*- 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: return None # 根节点 root = TreeNode(pre[0]) # 根节点在中序遍历中的位置索引 index = tin.index(pre[0]) # 递归 构造树的左子树 root.left = self.reConstructBinaryTree(pre[1:index+1], tin[:index]) # 递归构造树的右子树 root.right = self.reConstructBinaryTree(pre[index+1:], tin[index+1:]) return root # write code here