Programming Code Examples

How to delete a node from Binary Search Tree (BST) in Java5 min read

In a Binary Tree, each node can have at most two nodes. For a binary tree to be a binary search tree (BST), the data of all the nodes in the left sub-tree of the root node should be less than or equals to the data of the root. The data of all the nodes in the right subtree of the root node should be greater than the data of the root.

Deleting a node from Binary search tree is little complicated compare to inserting a node. It includes two steps:

  1. Search the node with given value.
  2. Delete the node.




The algorithm has 3 cases while deleting node:

  1. Node to be deleted has is a leaf node (no children).
  2. Node to be deleted has one child (eight left or right child node).
  3. Node to be deleted has two nodes.

We will use simple recursion to find the node and delete it from the tree.

Here is the steps to delete a node from binary search tree:

Case 1: Node to be deleted has is a leaf node (no children).

  1. This is very simple implementation. First find the node reference with given value.
  2. Set corresponding link of the parent node to null. With this the node to be deleted lost its connectivity and eligible for garbage collection.

Case 2: Node to be deleted has one child (eight left or right child node).

  1. First find the node reference with given value.
  2. Take the reference of the child node and assign its reference to the corresponding link of the parent node. With this the node to be deleted lost its connectivity and eligible for garbage collection.

Case 3: Node to be deleted has two nodes.

  1. It is little complicated process.
  2. First find the node reference with given value.
  3. Find the minimum/maximum value of the right/left sub tree.
  4. Replace the node value with the minimum/maximum value.
  5. Now delete the minimum/maximum value from the nodes right/left sub tree.

We will use below binary tree for our code output:

How to delete a node from Binary Search Tree (BST) in Java
How to delete a node from Binary Search Tree (BST) in Java

BinarySearchTreeImpl

BTSNode:

Output:

Add comment