Sai A Sai A
Updated date Jun 30, 2023
In this blog, we dive into the world of Binary Search Trees (BSTs) and provide a practical implementation in C#. With step-by-step explanations and complete code examples, you'll learn how to set up a BST class, insert nodes, search for values, delete nodes, and traverse the tree.
  • 2.1k
  • 0
  • 0

Introduction:

Binary Search Trees (BSTs) are fundamental data structures in computer science, known for their efficient search and retrieval capabilities. In this blog post, we will delve into the concepts behind Binary Search Trees and provide a comprehensive implementation in C#. By following along with the code and explanations, you will gain a solid understanding of BSTs and be able to utilize them in your own projects.

Method 1: Setting Up the BST Class

Let's begin by defining the structure of our Binary Search Tree class. We will create a Node class to represent each node in the tree and a BST class to handle tree operations. Below is the code for the initial setup:

using System;

public class Node
{
    public int Data;
    public Node Left;
    public Node Right;
    
    public Node(int data)
    {
        Data = data;
        Left = null;
        Right = null;
    }
}

public class BST
{
    public Node Root;
    
    public BST()
    {
        Root = null;
    }
}

Method 2: Inserting Nodes

The next step is to implement the logic for inserting nodes into the BST. We will explain the process of finding the correct position for a new node and creating the appropriate connections. Here's the code for inserting nodes:

public void Insert(int data)
{
    Node newNode = new Node(data);
    
    if (Root == null)
    {
        Root = newNode;
    }
    else
    {
        Node current = Root;
        Node parent;
        
        while (true)
        {
            parent = current;
            
            if (data < current.Data)
            {
                current = current.Left;
                
                if (current == null)
                {
                    parent.Left = newNode;
                    break;
                }
            }
            else
            {
                current = current.Right;
                
                if (current == null)
                {
                    parent.Right = newNode;
                    break;
                }
            }
        }
    }
}

Let's insert some nodes into the tree:

BST bst = new BST();
bst.Insert(50);
bst.Insert(30);
bst.Insert(70);
bst.Insert(20);
bst.Insert(40);

Output after inserting nodes:

50
/  \
30   70
/  \
20   40

Method 3: Searching for Nodes

Searching for nodes is a vital operation in a BST. The structure of the tree enables efficient searching. Below is the code for the search function:

public bool Search(int data)
{
    Node current = Root;
    
    while (current != null)
    {
        if (data == current.Data)
        {
            return true;
        }
        else if (data < current.Data)
        {
            current = current.Left;
        }
        else
        {
            current = current.Right;
        }
    }
    
    return false;
}

Let's search for a value in the tree:

bool found = bst.Search(40);
Console.WriteLine("Is 40 present in the BST? " + found);

Output:

Is 40 present in the BST? True

Method 4: Deleting Nodes

Deleting nodes in a BST can be complex. We need to handle different scenarios based on the node's position and its children. Here's the code for deleting nodes:

public bool Delete(int data)
{
    Node current = Root;
    Node parent = Root;
    bool isLeftChild = true;
    
    while (current.Data != data)
    {
        parent = current;
        
        if (data < current.Data)
        {
            current = current.Left;
            isLeftChild = true;
        }
        else
        {
            current = current.Right;
            isLeftChild = false;
        }
        
        if (current == null)
        {
            return false;
        }
    }
    
    // Code for handling different deletion scenarios goes here
    
    return true;
}

Please note that handling different deletion scenarios (e.g., no children, one child, or two children) is beyond the scope of this blog post. However, you can explore those scenarios further to complete the implementation.

Method 5: Traversing the Tree

Traversing the BST allows us to visit each node in a specific order. Here's the code for three common traversal methods: Inorder, Preorder, and Postorder.

public void InorderTraversal(Node node)
{
    if (node != null)
    {
        InorderTraversal(node.Left);
        Console.Write(node.Data + " ");
        InorderTraversal(node.Right);
    }
}

public void PreorderTraversal(Node node)
{
    if (node != null)
    {
        Console.Write(node.Data + " ");
        PreorderTraversal(node.Left);
        PreorderTraversal(node.Right);
    }
}

public void PostorderTraversal(Node node)
{
    if (node != null)
    {
        PostorderTraversal(node.Left);
        PostorderTraversal(node.Right);
        Console.Write(node.Data + " ");
    }
}

Let's perform the traversals on our tree:

Console.WriteLine("Inorder Traversal:");
bst.InorderTraversal(bst.Root);
Console.WriteLine("\nPreorder Traversal:");
bst.PreorderTraversal(bst.Root);
Console.WriteLine("\nPostorder Traversal:");
bst.PostorderTraversal(bst.Root);

Output:

Inorder Traversal:
20 30 40 50 70 
Preorder Traversal:
50 30 20 40 70 
Postorder Traversal:
20 40 30 70 50

Conclusion:

In this practical implementation guide, we explored Binary Search Trees (BSTs) and implemented one in C#. We covered the essential methods involved in working with BSTs, including inserting nodes, searching for nodes, deleting nodes, and traversing the tree. By following the explanations and executing the provided code, you now have a strong foundation in working with BSTs and can apply this knowledge to your own programming endeavors.

Comments (0)

There are no comments. Be the first to comment!!!