Binary Search Tree in C#: Add, Find, Remove and Traversals

A binary tree is a tree where each node has at most two children, called left and right. A binary search tree (BST) adds one rule: every value in a node’s left subtree is smaller than the node’s value, and every value in its right subtree is larger. That rule lets you find, add or remove a value by walking a single path from the root, much like a binary search on a sorted array.

The implementation below is generic, so it stores any type that implements IComparable<T>, and it ignores duplicates the way a set does.

The tree class

public enum TraversalOrder { PreOrder, InOrder, PostOrder }

public sealed class BinarySearchTree<T> where T : IComparable<T>
{
    private sealed class Node(T value)
    {
        public T Value = value;
        public Node? Left;
        public Node? Right;
    }

    private Node? _root;

    public int Count { get; private set; }

    public bool Add(T value)
    {
        if (_root is null)
        {
            _root = new Node(value);
            Count++;
            return true;
        }

        Node current = _root;
        while (true)
        {
            int c = value.CompareTo(current.Value);
            if (c == 0) return false;   // already in the tree

            if (c < 0)
            {
                if (current.Left is null) { current.Left = new Node(value); break; }
                current = current.Left;
            }
            else
            {
                if (current.Right is null) { current.Right = new Node(value); break; }
                current = current.Right;
            }
        }

        Count++;
        return true;
    }

    public bool Contains(T value)
    {
        Node? current = _root;
        while (current is not null)
        {
            int c = value.CompareTo(current.Value);
            if (c == 0) return true;
            current = c < 0 ? current.Left : current.Right;
        }
        return false;
    }

    public bool Remove(T value)
    {
        _root = Remove(_root, value, out bool removed);
        if (removed) Count--;
        return removed;
    }

    private static Node? Remove(Node? node, T value, out bool removed)
    {
        if (node is null)
        {
            removed = false;
            return null;
        }

        int c = value.CompareTo(node.Value);
        if (c < 0)
        {
            node.Left = Remove(node.Left, value, out removed);
        }
        else if (c > 0)
        {
            node.Right = Remove(node.Right, value, out removed);
        }
        else
        {
            removed = true;

            // Zero or one child: replace the node with that child.
            if (node.Left is null) return node.Right;
            if (node.Right is null) return node.Left;

            // Two children: take the smallest value of the right subtree,
            // then remove that value from the right subtree.
            Node successor = node.Right;
            while (successor.Left is not null)
                successor = successor.Left;

            node.Value = successor.Value;
            node.Right = Remove(node.Right, successor.Value, out _);
        }

        return node;
    }

    public int Height() => Height(_root);

    private static int Height(Node? node)
        => node is null ? 0 : 1 + Math.Max(Height(node.Left), Height(node.Right));

    public List<T> Traverse(TraversalOrder order)
    {
        List<T> result = new(Count);
        Traverse(_root, order, result);
        return result;
    }

    private static void Traverse(Node? node, TraversalOrder order, List<T> result)
    {
        if (node is null) return;

        if (order == TraversalOrder.PreOrder) result.Add(node.Value);
        Traverse(node.Left, order, result);
        if (order == TraversalOrder.InOrder) result.Add(node.Value);
        Traverse(node.Right, order, result);
        if (order == TraversalOrder.PostOrder) result.Add(node.Value);
    }
}

The Node class uses a primary constructor, which needs C# 12 (.NET 8). It is private, so callers never get a reference to a node and cannot break the ordering rule by changing a value or a link from outside.

Using the tree

var tree = new BinarySearchTree<int>();

foreach (int value in new[] { 1, 2, 7, 3, 10, 5, 8 })
    tree.Add(value);

Console.WriteLine($"Contains 5: {tree.Contains(5)}, height: {tree.Height()}");
Print(tree);

tree.Remove(7);
tree.Remove(8);

Console.WriteLine("After removing 7 and 8:");
Print(tree);

static void Print(BinarySearchTree<int> tree)
{
    foreach (TraversalOrder order in Enum.GetValues<TraversalOrder>())
        Console.WriteLine($"{order,-10}{string.Join(" ", tree.Traverse(order))}");
}

Output:

Contains 5: True, height: 5
PreOrder  1 2 7 3 5 10 8
InOrder   1 2 3 5 7 8 10
PostOrder 5 3 8 10 7 2 1
After removing 7 and 8:
PreOrder  1 2 10 3 5
InOrder   1 2 3 5 10
PostOrder 5 3 10 2 1

Traversals

All three traversals visit every node once; they differ only in when the node itself is visited relative to its subtrees. The single Traverse method above makes that visible: the three if lines are the only difference.

  • Pre-order visits the node, then the left subtree, then the right. Replaying the values in this order into an empty tree rebuilds the same shape, which makes it the order to use for copying or serializing a tree.
  • In-order visits left, node, right. For a binary search tree this returns the values sorted, which is the quickest way to check that the tree is valid.
  • Post-order visits both subtrees before the node. Use it when children must be handled before their parent, such as freeing resources or evaluating an expression tree.

Removing a node

Removal has three cases. A leaf is simply unlinked. A node with one child is replaced by that child. A node with two children cannot be unlinked without orphaning a subtree, so its value is replaced with the next larger value in the tree (the leftmost node of the right subtree, called the in-order successor), and that successor, which has at most one child, is removed instead.

In the example, removing 7 copies 8 into its place and deletes the old 8 node. The second call then removes the new 8, whose successor is 10.

Performance and the balance problem

Add, Contains and Remove all walk one path from the root, so their cost is O(h), where h is the height of the tree. A tree built from random input has a height of about O(log n). But the shape depends entirely on the insertion order. The example inserts 1 and 2 first, so everything else hangs off the right side, and the tree is already five levels deep for seven values. Insert sorted data and every node gets only a right child: the tree degenerates into a linked list, every operation becomes O(n), and the recursive Remove, Height and Traverse methods can overflow the stack on large inputs.

The same five values stored in three valid binary search trees of depth 3, 4 and 5

The three trees above hold exactly the same values. Only the insertion order differs, and with it the number of steps a lookup can take.

Self-balancing trees (red-black, AVL) fix this by restructuring on insert and delete. .NET already ships one: SortedSet<T> and SortedDictionary<TKey, TValue> are red-black trees with guaranteed O(log n) operations, in-order enumeration and range queries through GetViewBetween. Use those in production code, and write your own tree when you need to learn the structure or need a variation the built-in types do not offer.

Related examples

13 thoughts on “Binary Search Tree in C#: Add, Find, Remove and Traversals”

  1. Your implementation doesn’t work because you commented out some of the code on line 12.

    It should be:

    12:
    if (value after.Data) //Is new node in right tree?
    after = after.RightNode;

    Here is a modified version with the fix, and some additional code for testing:

    /**
    * Original Author Turgay, http://csharpexamples.com/c-binary-search-tree-implementation/
    * Modified by Paul Mehta 2019/11/05
    **/
    using System;
    using System.Collections.Generic;

    namespace InterviewPrep
    {
    public class BinaryTreeTest
    {
    static void TestBinaryTree(int[] values)
    {
    BinaryTree bt = new BinaryTree(values);
    Console.WriteLine(” Depth: ” + bt.GetTreeDepth());

    bt.TraverseInOrder();
    bt.TraversePreOrder();
    bt.TraversePostOrder();

    if (values.Length >= 2)
    {
    Console.WriteLine(” Removing value { ” + values[1] + ” }”);
    bt.Remove(values[1]);
    bt.TraverseInOrder();
    bt.TraversePreOrder();
    bt.TraversePostOrder();
    }

    Console.WriteLine(“\n”);
    }

    public static void Main(string[] args)
    {
    int[] arr1 = { 1, 2, 7, 3, 10, 5, 8, 8, 9 };
    int[] arr2 = { 1, 3, 6, 2, 7, 5, 4, 8, 9 };
    int[] arr3 = { -10, 10, -20, 0, 17, 19, 4, 8, 9, -30, -5 };

    TestBinaryTree(arr1);
    TestBinaryTree(arr2);
    TestBinaryTree(arr3);

    Console.ReadLine();
    }

    }

    class Node
    {
    public Node LeftNode { get; set; }
    public Node RightNode { get; set; }
    public int Data { get; set; }
    }

    class BinaryTree
    {
    public BinaryTree()
    {

    }

    public BinaryTree(int[] values)
    {
    Console.WriteLine(“BinaryTree { ” + string.Join(“,”, values) + ” }”);

    foreach (int i in values)
    {
    Add(i);
    }
    }

    public Node Root { get; set; }

    public bool Add(int value)
    {
    Node before = null, after = this.Root;

    while (after != null)
    {
    before = after;
    if (value after.Data) //Is new node in right tree?
    after = after.RightNode;
    else
    {
    //Exist same value
    return false;
    }
    }

    Node newNode = new Node();
    newNode.Data = value;

    if (this.Root == null)//Tree ise empty
    this.Root = newNode;
    else
    {
    if (value < before.Data)
    before.LeftNode = newNode;
    else
    before.RightNode = newNode;
    }

    return true;
    }

    public Node Find(int value)
    {
    return this.Find(value, this.Root);
    }

    public void Remove(int value)
    {
    Remove(this.Root, value);
    }

    private Node Remove(Node parent, int key)
    {
    if (parent == null) return parent;

    if (key parent.Data)
    parent.RightNode = Remove(parent.RightNode, key);

    // if value is same as parent’s value, then this is the node to be deleted
    else
    {
    // node with only one child or no child
    if (parent.LeftNode == null)
    return parent.RightNode;
    else if (parent.RightNode == null)
    return parent.LeftNode;

    // node with two children: Get the inorder successor (smallest in the right subtree)
    parent.Data = MinValue(parent.RightNode);

    // Delete the inorder successor
    parent.RightNode = Remove(parent.RightNode, parent.Data);
    }

    return parent;
    }

    private int MinValue(Node node)
    {
    int minv = node.Data;

    while (node.LeftNode != null)
    {
    minv = node.LeftNode.Data;
    node = node.LeftNode;
    }

    return minv;
    }

    private Node Find(int value, Node parent)
    {
    if (parent != null)
    {
    if (value == parent.Data) return parent;
    if (value < parent.Data)
    return Find(value, parent.LeftNode);
    else
    return Find(value, parent.RightNode);
    }

    return null;
    }

    public int GetTreeDepth()
    {
    return this.GetTreeDepth(this.Root);
    }

    private int GetTreeDepth(Node parent)
    {
    return parent == null ? 0 : Math.Max(GetTreeDepth(parent.LeftNode), GetTreeDepth(parent.RightNode)) + 1;
    }

    public void TraversePreOrder()
    {
    Console.Write(" Traverse Pre Order: \t");
    TraversePreOrder(this.Root);
    Console.WriteLine();
    }
    public void TraversePreOrder(Node parent)
    {
    if (parent != null)
    {
    Console.Write(parent.Data + " ");
    TraversePreOrder(parent.LeftNode);
    TraversePreOrder(parent.RightNode);
    }
    }

    public void TraverseInOrder()
    {
    Console.Write(" Traverse In Order: \t");
    TraverseInOrder(this.Root);
    Console.WriteLine();
    }
    public void TraverseInOrder(Node parent)
    {
    if (parent != null)
    {
    TraverseInOrder(parent.LeftNode);
    Console.Write(parent.Data + " ");
    TraverseInOrder(parent.RightNode);
    }
    }

    public void TraversePostOrder()
    {
    Console.Write(" Traverse Post Order: \t");
    TraversePostOrder(this.Root);
    Console.WriteLine();

    }
    public void TraversePostOrder(Node parent)
    {
    if (parent != null)
    {
    TraversePostOrder(parent.LeftNode);
    TraversePostOrder(parent.RightNode);
    Console.Write(parent.Data + " ");
    }
    }
    }

    }

    Reply
  2. I have small doubt about the code,
    when you assign condition, for Root node. on line 26

    if (this.Root == null)//Tree is empty
    this.Root = newNode;

    this does not have properties of RightNode or LeftNode Object which is null.
    So the program will crash on second iteration, because when you check on line 12 the object of afterLeftNode is NULL

    if (value after.Data) //Is new node in right tree?
    after = after.RightNode;

    another question should ask also, is it the root is purposely not define
    the LeftNode or RightNode
    ?

    Reply
  3. Thank you so much for your code. It is really helpful.
    But there is one major problem.
    The value at the root will never be deleted.
    In your sample, 1 cannot be deleted. Could you fix it please

    Reply
  4. Hi, thanks so much for the code. Could I ask, how do you print out the depth and whether or not an element is in the tree? (sorry if this seems really basic haha)

    Reply
  5. This is how I implemented the adding logic(with a little recursion it’s more friendly 🙂 )

    public bool Add(int value)
    {
    var newNode = new Node {Data = value};

    if (Root == null)
    {
    Root = newNode;
    return true;
    }

    return AddChildNode(newNode, Root);
    }

    private bool AddChildNode(Node newNode, Node parent)
    {
    if (newNode.Data > parent.Data)
    {
    if (parent.RightNode == null)
    parent.RightNode = newNode;
    else
    AddChildNode(newNode, parent.RightNode);

    }
    else
    {
    if (parent.LeftNode == null)
    parent.LeftNode = newNode;
    else
    AddChildNode(newNode, parent.LeftNode);
    }

    return true;
    }

    Reply

Leave a Comment