MediumNo. 0450

Delete Node in a BST — LeetCode 450 Python Solution

Topics
Tree, Binary Search Tree, Binary Tree
On a study list
LeetCode 75
Reading time
5 min

The problem

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Example

Input
root = [5,3,6,2,4,null,7], key = 3
Output
[5,4,6,2,null,null,7]
Explanation
Given key to delete is 3. So we find the node with value 3 and delete it.

Python solution

PythonSolution
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
        if root is None:
            return None
        if root.val > key:
            root.left = self.deleteNode(root.left, key)
            return root
        if root.val < key:
            root.right = self.deleteNode(root.right, key)
            return root
        if root.left is None:
            return root.right
        if root.right is None:
            return root.left
        node = root.right
        while node.left:
            node = node.left
        node.left = root.left
        root = root.right
        return root

Complexity

Time
O(n)
Space · auxiliary
O(h)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 450. Delete Node in a BST is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Tree, Binary Tree and Binary Search Tree.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 450. Delete Node in a BST?

LeetCode 450. Delete Node in a BST is rated Medium on LeetCode.

What is the time complexity of LeetCode 450. Delete Node in a BST?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 450. Delete Node in a BST?

The Python solution on this page uses O(h) auxiliary space.

What topics does LeetCode 450. Delete Node in a BST cover?

LeetCode 450. Delete Node in a BST is tagged Tree, Binary Search Tree and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.