Python recursive solution: replace the deleted node's val with its predecessor's val


  • 0
    class Solution(object):
        def delete(self, root, cur):
            if cur.right:
                cur.right = self.delete(root, cur.right)
                return cur
            root.val = cur.val
            return cur.left
        
        def deleteNode(self, root, key):
            if root == None:
                return None
            elif root.val == key:
                if root.left == None:
                    return root.right
                else:
                    root.left = self.delete(root, root.left)
            elif key < root.val:
                root.left = self.deleteNode(root.left, key)
            else:
                root.right = self.deleteNode(root.right, key)
            return root
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.