Delete Node in a BST — LeetCode 450 Python Solution

MediumTreeBinary Search TreeBinary Tree
Problem
#450
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

Python
# 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

MeasureComplexity
TimeO(n)
SpaceO(h) auxiliary

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

On a study list

This problem is on LeetCode 75.

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.

Get Stealth Interview