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
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
def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ tail = TreeNode(0) queue = [root] if root else [] while queue: node = queue.pop() if node.right: queue.append(node.right) if node.left: queue.append(node.left) node.left = None tail.right = node tail = tail.right
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