Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Forked from primaryobjects/bst-delete-node.js
Created September 4, 2018 20:38
Show Gist options
  • Save lbvf50mobile/fbf67ebb379831bc49b6255cce8af0fa to your computer and use it in GitHub Desktop.
Save lbvf50mobile/fbf67ebb379831bc49b6255cce8af0fa to your computer and use it in GitHub Desktop.
Delete a node in a Binary Search Tree BST.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} key
* @return {TreeNode}
*/
var deleteNode = function(root, key) {
// Find node to delete.
if (root !== null) {
var current = root;
var stack = [];
while (current) {
stack.push(current);
if (current.val === key) {
// Found the node to delete.
stack.pop();
var parent = stack.pop();
if (!current.left && !current.right) {
// No children, just remove the node.
if (parent && parent.left && parent.left.val === current.val) {
parent.left = null;
}
else if (parent) {
parent.right = null;
}
else {
// No parent, this must be the root node.
root = [];
}
}
else if (current.left && !current.right) {
// One left child node.
if (parent && parent.left && parent.left.val === current.val) {
parent.left = current.left;
}
else if (parent) {
parent.right = current.left;
}
else {
// No parent, this must be the root node.
root = current.left;
}
}
else if (current.right && !current.left) {
// One right child node.
if (parent && parent.left && parent.left.val === current.val) {
parent.left = current.right;
}
else if (parent) {
parent.right = current.right;
}
else {
// No parent, this must be the root node.
root = current.right;
}
}
else {
// Node has 2 children.
// First, find the minimum element in the right subtree of the node to be removed.
var minNode = current.right;
while (minNode) {
if (minNode.left) {
minNode = minNode.left;
}
else {
// We're at the bottom of the subtree.
break;
}
}
// Delete minNode.
current = deleteNode(current, minNode.val);
// Replace value.
current.val = minNode.val;
}
break;
}
else if (key < current.val) {
current = current.left;
}
else if (key > current.val) {
current = current.right;
}
}
}
return root;
};
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.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).
Example:
root = [5,3,6,2,4,null,7]
key = 3
5
/ \
3 6
/ \ \
2 4 7
Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the following BST.
5
/ \
4 6
/ \
2 7
Another valid answer is [5,2,6,null,4,null,7].
5
/ \
2 6
\ \
4 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment