class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root:
return None
if root.val < key:
root.right = self.deleteNode(root.right, key)
elif root.val > key:
root.left = self.deleteNode(root.left, key)
else:
if not root.left:
return root.right
if not root.right:
return root.left
else:
node = root.right
while node.left:
node = node.left
node.left = root.left
root = root.right
return root
时间复杂度:O()
空间复杂度:O()
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if root is None:
return None
if root.val == key:
if root.left is None and root.right is None: # 一开始漏了这里的条件
return None
if root.left is None and root.right is not None:
return root.right
if root.right is None and root.left is not None:
return root.left
if root.right is not None and root.left is not None:
cur = root.right
while cur.left is not None:
cur = cur.left
cur.left = root.left
return root.right
if root.val > key:
root.left = self.deleteNode(root.left, key)
if root.val < key:
root.right = self.deleteNode(root.right, key)
return root
[Given a binary tree, how do you remove all the half nodes?]
def RemoveHalfNodes(root):
if root is None:
return None
root.left = RemoveHalfNodes(root.left)
root.right = RemoveHalfNodes(root.right)
# if both left and right child is None
# the node is not a Half node
if root.left is None and root.right is None:
return root
# If current nodes is a half node with left child
# None then it's right child is returned and
# replaces it in the given tree
if root.left is None:
new_root = root.right
temp = root
root = None
del(temp)
return new_root
if root.right is None:
new_root = root.left
temp = root
root = None
del(temp)
return new_root
return root