Exemplo n.º 1
0
 def helper(self, nums):
     if len(nums) == 0:
         return None
     pivot = len(nums) // 2
     root = TreeNode(nums[pivot])
     root.left = self.helper(nums[:pivot])
     root.right = self.helper(nums[pivot + 1:])
     return root
Exemplo n.º 2
0
  def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
    if preorder is None or len(preorder) != len(inorder) or len(preorder) == 0:
      return None

    i = 0
    while i < len(inorder) and inorder[i] != preorder[0]:
      i += 1
    root = TreeNode(preorder[0])
    root.left = self.buildTree(preorder[1:i + 1], inorder[0:i])
    root.right = self.buildTree(preorder[i + 1:], inorder[i + 1:])
    return root
Exemplo n.º 3
0
    def generate(self, start, end):
        if start > end:
            return [None]

        if start == end:
            return [TreeNode(start)]

        result = []
        for num in range(start, end + 1):
            lefts = self.generate(start, num - 1)
            rights = self.generate(num + 1, end)
            for left in lefts:
                for right in rights:
                    root = TreeNode(num)
                    root.left = left
                    root.right = right
                    result.append(root)
        return result