题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pre int整型一维数组 # @param vin int整型一维数组 # @return TreeNode类 # class Solution: def find_pre(self,tvin,opre): ret=[] for item in opre: if item in tvin: ret.append(item) return ret def reConstructBinaryTree(self , pre: List[int], vin: List[int]) -> TreeNode: # write code here if len(pre)==0: return root=pre[0] rettree=TreeNode(root) if len(pre)==1: return rettree opre=pre[1:] root_index=vin.index(root) left_vin=vin[:root_index] left_pre=self.find_pre(left_vin,opre) rettree.left=self.reConstructBinaryTree(left_pre,left_vin) right_vin=vin[root_index+1:] right_pre=self.find_pre(right_vin,opre) rettree.right=self.reConstructBinaryTree(right_pre,right_vin) return rettree