Binary Search Tree Implementation in C#

Introduction

This article presents a binary search tree implementation in C#, designed to be concise and easy to understand. We will discuss the interface definition, followed by the implementation of search, insert, delete, and update operations. Binary search trees (BSTs) are a widely used data structure due to their efficient search, insertion, and deletion capabilities. A BST is a tree-like data structure where each node has at most two children, and for all nodes, the left child node is less than the parent node, and the right child node is greater than the parent node. The time complexity for search, insert, and delete operations is generally O(h), where h is the height of the tree. In a balanced tree, the height is O(log n), where n is the number of nodes.

Binary Search Tree Implementation in C#

Binary Search Tree C# Interface Definition

To implement a binary search tree in C#, we first define an interface IBinarySearchTree<T> that extends the IComparable interface for type T. This constraint ensures that the items stored in the tree can be compared, which is a fundamental requirement for the operations of a binary search tree. The interface exposes four main methods: Search, Insert, Delete, and Update.

/// <summary>
/// Represents a generic binary search tree interface, defining the essential operations
/// required for a binary search tree.
/// </summary>
/// <typeparam name="T">The type of items stored in the binary search tree.
/// This type must implement the IComparable interface to enable comparisons.</typeparam>
public interface IBinarySearchTree<T> where T : IComparable<T>
{
    /// <summary>
    /// Searches for the specified item in the binary search tree.
    /// </summary>
    /// <param name="item">The item to search for.</param>
    /// <returns>True if the item is found in the tree, otherwise false.</returns>
    bool Search(T item);

    /// <summary>
    /// Inserts the specified item into the binary search tree while maintaining the
    /// binary search tree property.
    /// </summary>
    /// <param name="item">The item to insert.</param>
    /// <returns>True if the item is successfully inserted, otherwise false (e.g., when the item already exists in the tree).</returns>
    bool Insert(T item);

    /// <summary>
    /// Deletes the specified item from the binary search tree and rearranges the
    /// tree to maintain the binary search tree property.
    /// </summary>
    /// <param name="item">The item to delete.</param>
    /// <returns>True if the item is successfully deleted, otherwise false (e.g., when the item is not found in the tree).</returns>
    bool Delete(T item);

    /// <summary>
    /// Updates an existing item in the binary search tree with a new item while
    /// maintaining the binary search tree property.
    /// </summary>
    /// <param name="oldItem">The item to be replaced in the tree.</param>
    /// <param name="newItem">The new item that will replace the old item.</param>
    /// <returns>True if the update operation is successful, otherwise false (e.g., when the old item is not found in the tree).</returns>
    bool Update(T oldItem, T newItem);
}

public class BinarySearchTree<T> : IBinarySearchTree<T> where T : IComparable<T>
{
    private class TreeNode
    {
        public T Value;
        public TreeNode Left;
        public TreeNode Right;

        public TreeNode(T value)
        {
            Value = value;
            Left = null;
            Right = null;
        }
    }

    private TreeNode root;

    public BinarySearchTree()
    {
        root = null;
    }

    //The code continues below...
}
  • The Search operation checks if an item exists within the tree, and returns true if found, otherwise false. The time complexity of the search operation is O(h), where h is the height of the tree.
  • The Insert operation adds a new item to the tree while maintaining the binary search tree property. The time complexity of the insert operation is O(h), where h is the height of the tree.
  • The Delete operation removes an item from the tree and rearranges the tree to maintain its properties. The time complexity of the delete operation is O(h), where h is the height of the tree.
  • The Update operation updates an existing item in the tree with a new item while maintaining the binary search tree property. The time complexity of the update operation is O(h), where h is the height of the tree.

The next sections of this article will explain the implementations of these operations, ensuring efficient performance while maintaining the binary search tree properties.

Search Operation Implementation in Binary Search Tree

In the search operation, we traverse the tree, starting from the root node, comparing the target item with each node’s value. If the target item is less than the current node’s value, we move to the left child; otherwise, we move to the right child. Whenever we reach a null reference, the item is not in the tree, and we return false. If we find a node with the same value as the target item, we return true. The time complexity of the search operation is O(h), where h is the height of the tree. In the worst case, we need to traverse the entire height of the tree.

/// <summary>
/// Searches for the specified item in the binary search tree using a recursive algorithm.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>True if the item is found in the tree, otherwise false.</returns>
public bool Search(T item)
{
    return SearchRecursive(root, item);
}

/// <summary>
/// Recursively searches for the specified item in the binary search tree, starting from the given node.
/// </summary>
/// <param name="node">The node from which to start the search.</param>
/// <param name="item">The item to search for.</param>
/// <returns>True if the item is found in the subtree rooted at the given node, otherwise false.</returns>
private bool SearchRecursive(TreeNode node, T item)
{
    if (node == null)
    {
        return false;
    }

    int compareResult = item.CompareTo(node.Value);
    if (compareResult == 0)
    {
        return true;
    }
    else if (compareResult < 0)
    {
        return SearchRecursive(node.Left, item);
    }
    else
    {
        return SearchRecursive(node.Right, item);
    }
}

Insert Operation Implementation in Binary Search Tree

The insert operation adds a new item to the tree while maintaining the binary search tree property. In the insert operation, we traverse the tree to find the position for the new item. We compare the new item with each node’s value during the traversal. If the new item is less than the current node’s value, we move to the left child; otherwise, we move to the right child. If we find a node with the same value as the new item, the insertion is a duplicate, and we return false. Once we reach a null reference, we have found the position for the new item. We then create a new node with the given item and update the parent node’s reference. The time complexity of the insert operation is O(h), where h is the height of the tree.

/// <summary>
/// Inserts the specified item into the binary search tree while maintaining the
/// binary search tree property, using a recursive algorithm.
/// </summary>
/// <param name="item">The item to insert.</param>
/// <returns>True if the item is successfully inserted, otherwise false (e.g., when the item already exists in the tree).</returns>
public bool Insert(T item)
{
    if (root == null)
    {
        root = new TreeNode(item);
        return true;
    }

    return InsertRecursive(root, item);
}

/// <summary>
/// Recursively inserts the specified item into the binary search tree, starting from the given node.
/// </summary>
/// <param name="node">The node from which to start the insertion.</param>
/// <param name="item">The item to insert.</param>
/// <returns>True if the item is successfully inserted in the subtree rooted at the given node, otherwise false (e.g., when the item already exists in the subtree).</returns>
private bool InsertRecursive(TreeNode node, T item)
{
    int compareResult = item.CompareTo(node.Value);
    if (compareResult == 0)
    {
        return false;
    }
    else if (compareResult < 0)
    {
        if (node.Left == null)
        {
            node.Left = new TreeNode(item);
            return true;
        }
        else
        {
            return InsertRecursive(node.Left, item);
        }
    }
    else
    {
        if (node.Right == null)
        {
            node.Right = new TreeNode(item);
            return true;
        }
        else
        {
            return InsertRecursive(node.Right, item);
        }
    }
}

Delete Operation Implementation

The delete operation removes an item from the tree and rearranges the tree to maintain the binary search tree property. It involves three main scenarios:

  1. The node to delete has no children: In this case, we simply remove the node from the tree and update its parent’s reference.
  2. The node to delete has one child: We remove the node from the tree and update its parent’s reference to point to the node’s single child.
  3. The node to delete has two children: We find the node with the minimum value in the right subtree (the inorder successor), replace the node to delete with the inorder successor’s value, and then delete the inorder successor.

The time complexity of the delete operation is O(h), where h is the height of the tree.

/// <summary>
/// Deletes the specified item from the binary search tree while maintaining the
/// binary search tree property, using a recursive algorithm.
/// </summary>
/// <param name="item">The item to delete.</param>
/// <returns>True if the item is successfully deleted, otherwise false (e.g., when the item is not found in the tree).</returns>
public bool Delete(T item)
{
    return DeleteRecursive(ref root, item);
}

/// <summary>
/// Recursively deletes the specified item from the binary search tree, starting from the given node.
/// </summary>
/// <param name="node">A reference to the node from which to start the deletion.</param>
/// <param name="item">The item to delete.</param>
/// <returns>True if the item is successfully deleted from the subtree rooted at the given node, otherwise false (e.g., when the item is not found in the subtree).</returns>
private bool DeleteRecursive(ref TreeNode node, T item)
{
    if (node == null)
    {
        return false;
    }

    int compareResult = item.CompareTo(node.Value);
    if (compareResult < 0)
    {
        return DeleteRecursive(ref node.Left, item);
    }
    else if (compareResult > 0)
    {
        return DeleteRecursive(ref node.Right, item);
    }
    else
    {
        if (node.Left == null && node.Right == null)
        {
            node = null;
        }
        else if (node.Left == null)
        {
            node = node.Right;
        }
        else if (node.Right == null)
        {
            node = node.Left;
        }
        else
        {
            T minValue = FindMinValue(node.Right);
            node.Value = minValue;
            DeleteRecursive(ref node.Right, minValue);
        }

        return true;
    }
}

/// <summary>
/// Finds the minimum value in the binary search tree rooted at the given node.
/// </summary>
/// <param name="node">The node from which to start searching for the minimum value.</param>
/// <returns>The minimum value in the subtree rooted at the given node.</returns>
private T FindMinValue(TreeNode node)
{
    while (node.Left != null)
    {
        node = node.Left;
    }

    return node.Value;
}

Update Operation Implementation

The update operation updates an existing item in the tree with a new item while maintaining the binary search tree property. In the update operation, we first delete the old item from the tree, and then insert the new item. The time complexity of the update operation is O(h), where h is the height of the tree. Since the update operation involves a delete followed by an insert, the complexity remains the same as individual delete and insert operations.

/// <summary>
/// Updates an existing item in the binary search tree with a new item while maintaining
/// the binary search tree property. This is done by deleting the old item and inserting the new item.
/// </summary>
/// <param name="oldItem">The item to be replaced in the binary search tree.</param>
/// <param name="newItem">The new item to replace the old item with.</param>
/// <returns>True if the update is successful, otherwise false (e.g., when the old item is not found in the tree).</returns>
public bool Update(T oldItem, T newItem)
{
    if (Delete(oldItem))
    {
        return Insert(newItem);
    }

    return false;
}

Conclusion

In this article, we presented a binary search tree implementation in C#, designed to be concise and easy to understand. We discussed the interface definition and provided an efficient implementation of search, insert, delete, and update operations, while maintaining the binary search tree properties. The binary search tree enables efficient manipulation of the data structure, with time complexities of O(h) for each operation, where h is the height of the tree. This non-concurrent implementation serves as a solid foundation for understanding the core concepts of binary search trees before moving on to more advanced, concurrent versions.

Correalted Resources

Tags: No tags

Comments are closed.