0
0
CsharpHow-ToBeginner · 4 min read

How to Implement Binary Tree in C# - Simple Guide

To implement a binary tree in C#, define a Node class with properties for Value, Left, and Right child nodes. Then create a BinaryTree class to manage the root node and tree operations like insertion and traversal.
📐

Syntax

A binary tree node typically has three parts: a value, a reference to the left child, and a reference to the right child. The Node class holds these. The BinaryTree class manages the root node and provides methods to add or traverse nodes.

csharp
public class Node
{
    public int Value;
    public Node Left;
    public Node Right;

    public Node(int value)
    {
        Value = value;
        Left = null;
        Right = null;
    }
}

public class BinaryTree
{
    public Node Root;

    public BinaryTree()
    {
        Root = null;
    }

    // Methods like Insert, Traverse can be added here
}
💻

Example

This example shows how to create a binary tree, insert values, and print them in order (left, root, right).

csharp
using System;

public class Node
{
    public int Value;
    public Node Left;
    public Node Right;

    public Node(int value)
    {
        Value = value;
        Left = null;
        Right = null;
    }
}

public class BinaryTree
{
    public Node Root;

    public BinaryTree()
    {
        Root = null;
    }

    public void Insert(int value)
    {
        Root = InsertRec(Root, value);
    }

    private Node InsertRec(Node root, int value)
    {
        if (root == null)
        {
            root = new Node(value);
            return root;
        }

        if (value < root.Value)
            root.Left = InsertRec(root.Left, value);
        else
            root.Right = InsertRec(root.Right, value);

        return root;
    }

    public void InOrderTraversal(Node node)
    {
        if (node == null) return;

        InOrderTraversal(node.Left);
        Console.Write(node.Value + " ");
        InOrderTraversal(node.Right);
    }
}

class Program
{
    static void Main()
    {
        BinaryTree tree = new BinaryTree();
        tree.Insert(50);
        tree.Insert(30);
        tree.Insert(70);
        tree.Insert(20);
        tree.Insert(40);
        tree.Insert(60);
        tree.Insert(80);

        Console.WriteLine("In-order traversal of binary tree:");
        tree.InOrderTraversal(tree.Root);
    }
}
Output
In-order traversal of binary tree: 20 30 40 50 60 70 80
⚠️

Common Pitfalls

Common mistakes include not initializing child nodes to null, which can cause errors when traversing. Another is inserting nodes incorrectly, breaking the binary search tree property. Also, forgetting to update the root node when inserting the first element can cause the tree to remain empty.

Always check for null before accessing child nodes and ensure your insert logic places smaller values to the left and larger to the right.

csharp
/* Wrong insertion: not updating root */
public void InsertWrong(int value)
{
    InsertRec(Root, value); // Root not updated
}

/* Correct insertion: update root */
public void InsertCorrect(int value)
{
    Root = InsertRec(Root, value); // Root updated
}
📊

Quick Reference

  • Node class: Holds value and left/right children.
  • BinaryTree class: Manages root and operations.
  • Insert method: Recursively adds nodes maintaining order.
  • Traversal: In-order prints sorted values.

Key Takeaways

Define a Node class with value, left, and right references to build a binary tree.
Use recursive methods to insert nodes and maintain the binary search tree property.
Always update the root node when inserting the first element.
Check for null before accessing child nodes to avoid errors.
In-order traversal prints the tree values in sorted order.