题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=295&tqId=23282&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
# 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 reConstructBinaryTree(self, pre: list[int], vin: list[int]) -> TreeNode: # write code here if not pre: return None node = TreeNode(pre[0]) index = vin.index(pre[0]) node.left = self.reConstructBinaryTree(pre[1 : index + 1], vin[:index]) node.right = self.reConstructBinaryTree(pre[index + 1 :], vin[index + 1 :]) return node