Concurrent Binary Search Tree Implementation in C#

Introduction

This article presents a concurrent 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 concurrent search, insert, delete, and update operations. Finally, we will provide an example of executing these operations concurrently. 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. In concurrent programming, multiple threads execute simultaneously, and concurrent access to shared data structures, such as a binary search tree, can lead to unpredictable results if not handled correctly. A concurrent binary search tree ensures that these operations are thread-safe, allowing multiple threads to access and modify the tree without causing data corruption or race conditions.

Concurrent Binary Search Tree Implementation in C#

Concurrent Binary Search Tree C# Interface Definition

To implement a concurrent binary search tree in C#, we first define an interface IConcurrentBinarySearchTree<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.

public interface IConcurrentBinarySearchTree<T> where T : IComparable<T>
{
    bool Search(T item);
    bool Insert(T item);
    bool Delete(T item);
    bool Update(T oldItem, T newItem);
}

/// <summary>
/// Concurrent Binary Search Tree implementation.
/// </summary>
public class ConcurrentBinarySearchTree<T> : IConcurrentBinarySearchTree<T> where T : IComparable<T>
{
    private Node<T> _root;
    private readonly object _lock = new object();
// Scroll down for methods implementation
// ...
}


  • 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 concurrent implementations of these operations, ensuring thread-safety and efficient performance while maintaining the binary search tree properties.

Concurrent Search Operation Implementation in Binary Search Tree

The concurrent search operation allows multiple threads to search for items within the binary search tree simultaneously without causing data corruption. The search operation does not modify the tree structure, so thread-safety is achieved without the need for locks or other synchronization mechanisms.

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.

public bool Search(T item)
    {
        // Traverses the tree, comparing each node's value with the target item.
        // If found, it returns true. Otherwise, it returns false.
        Node<T> current = _root;

        while (current != null)
        {
            int comparison = item.CompareTo(current.Value);

            if (comparison == 0)
                return true;
            current = comparison < 0 ? current.Left : current.Right;
        }

        return false;
    }

Concurrent Insert Operation Implementation in Binary Search Tree

The concurrent insert operation adds a new item to the tree while maintaining the binary search tree property. To ensure thread-safety, we use a lock when modifying the tree structure. This prevents multiple threads from inserting nodes simultaneously, which could lead to data corruption.

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 lock the tree to prevent other threads from modifying it while we insert the new node. The time complexity of the insert operation is O(h), where h is the height of the tree.

public bool Insert(T item)
    {
        // Inserts a new node by finding its position in the tree.
        // Uses a lock to ensure thread-safety during the process.
        Node<T> newNode = new Node<T>(item);
        Node<T> parent = null;
        Node<T> current = _root;

        while (current != null)
        {
            parent = current;
            int comparison = item.CompareTo(current.Value);

            if (comparison == 0)
                return false;
            current = comparison < 0 ? current.Left : current.Right;
        }

        lock (_lock)
        {
            if (parent == null)
                _root = newNode;
            else if (item.CompareTo(parent.Value) < 0)
                parent.Left = newNode;
            else
                parent.Right = newNode;
        }

        return true;
    }

Concurrent Delete Operation Implementation

The concurrent delete operation removes an item from the tree and rearranges the tree to maintain the binary search tree property. To ensure thread-safety, we use a lock when modifying the tree structure. The delete operation 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.

private void DeleteNode(Node<T> node, Node<T> parent)
{
    // Deletes a node from the tree and handles three scenarios:
    // 1. The node has no children.
    // 2. The node has one child.
    // 3. The node has two children.
    if (node.Left == null && node.Right == null)
    {
        ReplaceNodeInParent(parent, node, null);
    }
    else if (node.Left != null && node.Right != null)
    {
        Node<T> minRight = FindMinNode(node.Right);
        node.Value = minRight.Value;
        DeleteNode(minRight, node);
    }
    else
    {
        Node<T> child = node.Left ?? node.Right;
        ReplaceNodeInParent(parent, node, child);
    }
}

private void ReplaceNodeInParent(Node<T> parent, Node<T> node, Node<T> newNode)
{
    if (parent == null)
    {
        _root = newNode;
    }
    else if (parent.Left == node)
    {
        parent.Left = newNode;
    }
    else
    {
        parent.Right = newNode;
    }
}

private Node<T> FindMinNode(Node<T> node)
{
    while (node.Left != null)
    {
        node = node.Left;
    }

    return node;
}

Concurrent Update Operation Implementation

The concurrent update operation updates an existing item in the tree with a new item while maintaining the binary search tree property. To ensure thread-safety, we use a lock when modifying the tree structure. In the update operation, we first delete the old item from the tree, and then insert the new item. By using a lock, we ensure that no other thread can modify the tree between the delete and insert operations.

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.

public bool Update(T oldItem, T newItem)
{
    // Updates a node by deleting the old item and inserting the new one.
    // Uses locks to ensure thread-safety.
    lock (_lock)
    {
        if (Delete(oldItem))
            return Insert(newItem);
    }

    return false;
}
}

Testing the Concurrent Binary Search Tree

using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        IConcurrentBinarySearchTree<int> tree = new ConcurrentBinarySearchTree<int>();
        int elementCount = 50000;

        // Concurrent insertions
        var insertTask1 = Task.Run(() => InsertElements(tree, 1, elementCount / 2));
        var insertTask2 = Task.Run(() => InsertElements(tree, elementCount / 2 + 1, elementCount));

        Task.WaitAll(insertTask1, insertTask2);

        // Concurrent deletions
        var deleteTask1 = Task.Run(() => DeleteElements(tree, 1, elementCount / 4));
        var deleteTask2 = Task.Run(() => DeleteElements(tree, elementCount / 4 + 1, elementCount / 2));

        Task.WaitAll(deleteTask1, deleteTask2);

        // Concurrent updates
        var updateTask1 = Task.Run(() => UpdateElements(tree, 1, elementCount / 4, elementCount));
        var updateTask2 = Task.Run(() => UpdateElements(tree, elementCount / 4 + 1, elementCount / 2, elementCount));

        Task.WaitAll(updateTask1, updateTask2);

        Console.WriteLine("Processing completed.");
    }

    static void InsertElements(IConcurrentBinarySearchTree<int> tree, int start, int end)
    {
        for (int i = start; i <= end; i++)
        {
            tree.Insert(i);
        }
    }

    static void DeleteElements(IConcurrentBinarySearchTree<int> tree, int start, int end)
    {
        for (int i = start; i <= end; i++)
        {
            tree.Delete(i);
        }
    }

    static void UpdateElements(IConcurrentBinarySearchTree<int> tree, int start, int end, int offset)
    {
        for (int i = start; i <= end; i++)
        {
            tree.Update(i, i + offset);
        }
    }
}

Conclusion

In this article, we presented a concurrent binary search tree implementation in C#, designed to be concise and easy to understand. We discussed the interface definition and provided a thread-safe implementation of concurrent search, insert, delete, and update operations, while maintaining the binary search tree properties. The concurrent binary search tree enables efficient and safe manipulation of the data structure in a multi-threaded environment, with time complexities of O(h) for each operation, where h is the height of the tree.

Correlated Articles

Tags: No tags

Comments are closed.