if not preorder: return None # 空列表返回空树 r = TreeNode(preorder[0]) # 先序第一个元素一定是根 rid = inorder.index(preorder[0]) # 中序找出根,那么中序根左边是左子树,右边是右子树 r.left = self.buildTree(preorder[1:1+rid], inorder[:rid]) # 递归构造左子树 r.right = self.buildTree(preorder[rid+1:], inorder[rid+1:]) # 递归构造右子树 return r 作者:amir-6 链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/solution/python-6-xing-di-gui-jian-shu-by-amir-6/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: self.dic, self.po = {}, preorder for i in range(len(inorder)): self.dic[inorder[i]] = i return self.recur(0, 0, len(inorder) - 1) def recur(self, pre_root, in_left, in_right): if in_left > in_right: return # 终止条件:中序遍历为空 root = TreeNode(self.po[pre_root]) # 建立当前子树的根节点 i = self.dic[self.po[pre_root]] # 搜索根节点在中序遍历中的索引,从而可对根节点、左子树、右子树完成划分。 root.left = self.recur(pre_root + 1, in_left, i - 1) # 开启左子树的下层递归 root.right = self.recur(i - in_left + pre_root + 1, i + 1, in_right) # 开启右子树的下层递归 return root # 返回根节点,作为上层递归的左(右)子节点