Delete Node in a BST

medium bst tree recursion

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. Basically, the deletion can be divided into two stages: Search for a node to remove.

InputBST = [5, 3, 6, 2, 4, _, 7], v = 3
OutputBST = [5, 4, 6, 2, _, _, 7]
3 has two children; replace with successor 4, then delete 4 from the right subtree.

def delete_node(root, v):
    if root is None: return None
    if v < root.val: root.left = delete_node(root.left, v)
    elif v > root.val: root.right = delete_node(root.right, v)
    else:
        if root.left is None: return root.right
        if root.right is None: return root.left
        succ = root.right
        while succ.left: succ = succ.left
        root.val = succ.val
        root.right = delete_node(root.right, succ.val)
    return root
function deleteNode(root, v) {
  if (!root) return null;
  if (v < root.val) root.left = deleteNode(root.left, v);
  else if (v > root.val) root.right = deleteNode(root.right, v);
  else {
    if (!root.left) return root.right;
    if (!root.right) return root.left;
    let succ = root.right; while (succ.left) succ = succ.left;
    root.val = succ.val;
    root.right = deleteNode(root.right, succ.val);
  }
  return root;
}
class Solution {
    public TreeNode deleteNode(TreeNode root, int v) {
        if (root == null) return null;
        if (v < root.val) root.left = deleteNode(root.left, v);
        else if (v > root.val) root.right = deleteNode(root.right, v);
        else {
            if (root.left == null) return root.right;
            if (root.right == null) return root.left;
            TreeNode succ = root.right; while (succ.left != null) succ = succ.left;
            root.val = succ.val;
            root.right = deleteNode(root.right, succ.val);
        }
        return root;
    }
}
TreeNode* deleteNode(TreeNode* root, int v) {
    if (!root) return nullptr;
    if (v < root->val) root->left = deleteNode(root->left, v);
    else if (v > root->val) root->right = deleteNode(root->right, v);
    else {
        if (!root->left) return root->right;
        if (!root->right) return root->left;
        TreeNode* succ = root->right; while (succ->left) succ = succ->left;
        root->val = succ->val;
        root->right = deleteNode(root->right, succ->val);
    }
    return root;
}
Time: O(h) Space: O(h)