Python Fast and Clean Solution

  • 0
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution(object):
        def deleteNode(self, root, key):
            :type root: TreeNode
            :type key: int
            :rtype: TreeNode
            def right_most(node):
                pre = None
                while True:
                    if not node.right:
                        if pre: pre.right = node.left
                        return node.val
                    pre = node
                    node = node.right
            def delete(node):
                if not node: return None
                if node.val == key:
                    if not node.left: return node.right
                    if not node.right: return node.left
                    node.val = right_most(node.left)
                    if node.left.val == node.val: node.left = node.left.left
                    return node
                if node.val < key:
                    node.right = delete(node.right)
                    node.left = delete(node.left)
                return node
            return delete(root)

Log in to reply

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