def mid_ord(node: TreeNode) -> int: nonlocal accu_sum if node is None: return mid_ord(node.right) accu_sum += node.val node.val = accu_sum mid_ord(node.left)
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: if not root1 and not root2: return None new_tree = TreeNode(0) n1 = root1 if root1 else TreeNode(0) n2 = root2 if root2 else TreeNode(0) new_tree.val = n1.val + n2.val new_tree.left = self.mergeTrees(n1.left, n2.left) new_tree.right = self.mergeTrees(n1.right, n2.right) return new_tree
def deleteNode(self, root: TreeNode, key: int) -> TreeNode: if not root: return None if root.val == key: if not root.left: return root.right if not root.right: return root.left new_root = root.left while new_root.right: new_root = new_root.right root.val, new_root.val = new_root.val, root.val root.left = self.deleteNode(root.left, key) elif root.val > key: root.left = self.deleteNode(root.left, key) else: root.right = self.deleteNode(root.right, key) return root
def deleteNode(self, root: TreeNode, key: int) -> TreeNode: if not root: return root if root.val == key: if not root.left: return root.right elif not root.right: return root.left else: # Find successor succ = root.right while succ and succ.left: succ = succ.left root.val = succ.val root.right = self.deleteNode(root.right, succ.val) elif key < root.val: root.left = self.deleteNode(root.left, key) else: root.right = self.deleteNode(root.right, key) return root