def builtTree(): curr = next(preorder) if curr == 'null': return None node = TreeNode(int(curr)) node.left = builtTree() node.right = builtTree() return node
def reconstruct(left, right): if left > right: return None root = TreeNode(preorder.pop(0)) root.left = reconstruct(left, indexes[root.val] - 1) root.right = reconstruct(indexes[root.val] + 1, right) return root
def helper(left: ListNode, right: ListNode) -> TreeNode: if left == right: return None fast = slow = last = left while fast != right and fast.next != right: fast = fast.next.next last = slow slow = slow.next current = TreeNode(slow.val) current.left = helper(left, last) current.right = helper(slow.next, right) return current
def flatten(self, root: TreeNode) -> None: while root: if root.left and root.right: node = root.left while node.right: node = node.right node.right = root.right if root.left: root.right = root.left root.left = None root = root.right
def generate(start: int, end: int) -> List[TreeNode]: if start > end: return [None] ans = [] for i in range(start, end + 1): left, right = generate(start, i - 1), generate(i + 1, end) for l in left: for r in right: current = TreeNode(i) current.left = l current.right = r ans.append(current) return ans
def deleteNode(self, root: TreeNode, key: int) -> TreeNode: if not root: return root if root.val == key: if root.right: curr = root.right while curr.left: curr = curr.left curr.left = root.left return root.right else: return root.left elif root.val > key: root.left = self.deleteNode(root.left, key) else: root.right = self.deleteNode(root.right, key) return root
# if find(root.left, q) or find(root.right, q): # return root # elif find(root.left, p): # if root == q or find(root.right, q): return root # return self.lowestCommonAncestor( root.left, p, q) # else: # if root == q or find(root.left, q): return root # return self.lowestCommonAncestor( root.right, p, q) if __name__ == '__main__': instance = _236_Solution n0 = TreeNode(3) n1 = TreeNode(5) n2 = TreeNode(1) n3 = TreeNode(6) n4 = TreeNode(2) n5 = TreeNode(0) n6 = TreeNode(8) n7 = TreeNode(7) n8 = TreeNode(4) n0.left = n1 n0.right = n2 n1.left = n3 n1.right = n4 n2.left = n5 n2.right = n6 n4.left = n7 n4.right = n8 assert instance.lowestCommonAncestor(instance, n0, n1, n8) == n1