How to implement a tree data-structure in C#?

How to Implement a Tree Data Structure in C#

Implementing a tree data structure in C# involves defining the structure of a tree node and providing methods to manipulate the tree. Below is a basic implementation of a binary tree, which is a common type of tree data structure. In a binary tree, each node has at most two children, referred to as the left child and the right child.

Step-by-Step Implementation

  1. Define the Tree Node Class

The tree node class will have a value and references to its left and right children.

public class TreeNode { public int Value { get; set; } public TreeNode Left { get; set; } public TreeNode Right { get; set; } public TreeNode(int value) { Value = value; Left = null; Right = null; } }
  1. Define the Binary Tree Class

The binary tree class will contain the root node and methods to perform various operations like insertion, traversal, etc.

public class BinaryTree { public TreeNode Root { get; private set; } public BinaryTree() { Root = null; } public void Insert(int value) { Root = InsertRec(Root, value); } private TreeNode InsertRec(TreeNode root, int value) { if (root == null) { root = new TreeNode(value); return root; } if (value < root.Value) { root.Left = InsertRec(root.Left, value); } else if (value > root.Value) { root.Right = InsertRec(root.Right, value); } return root; } public void InOrderTraversal() { InOrderRec(Root); } private void InOrderRec(TreeNode root) { if (root != null) { InOrderRec(root.Left); Console.Write(root.Value + " "); InOrderRec(root.Right); } } public void PreOrderTraversal() { PreOrderRec(Root); } private void PreOrderRec(TreeNode root) { if (root != null) { Console.Write(root.Value + " "); PreOrderRec(root.Left); PreOrderRec(root.Right); } } public void PostOrderTraversal() { PostOrderRec(Root); } private void PostOrderRec(TreeNode root) { if (root != null) { PostOrderRec(root.Left); PostOrderRec(root.Right); Console.Write(root.Value + " "); } } public bool Search(int value) { return SearchRec(Root, value); } private bool SearchRec(TreeNode root, int value) { if (root == null) { return false; } if (root.Value == value) { return true; } return value < root.Value ? SearchRec(root.Left, value) : SearchRec(root.Right, value); } }
  1. Example Usage

Here is how you can use the BinaryTree class to create a tree, insert values, and perform traversals:

using System; public class Program { public static void Main() { BinaryTree tree = new BinaryTree(); // Insert values tree.Insert(50); tree.Insert(30); tree.Insert(70); tree.Insert(20); tree.Insert(40); tree.Insert(60); tree.Insert(80); // Perform traversals Console.Write("In-order traversal: "); tree.InOrderTraversal(); // Output: 20 30 40 50 60 70 80 Console.WriteLine(); Console.Write("Pre-order traversal: "); tree.PreOrderTraversal(); // Output: 50 30 20 40 70 60 80 Console.WriteLine(); Console.Write("Post-order traversal: "); tree.PostOrderTraversal(); // Output: 20 40 30 60 80 70 50 Console.WriteLine(); // Search for a value Console.WriteLine("Search 40: " + tree.Search(40)); // Output: True Console.WriteLine("Search 90: " + tree.Search(90)); // Output: False } }

Explanation

  1. TreeNode Class:

    • Represents a node in the binary tree.
    • Contains a value and references to left and right child nodes.
  2. BinaryTree Class:

    • Contains the root of the tree.
    • Provides methods for inserting values, performing in-order, pre-order, and post-order traversals, and searching for a value.
  3. Program Class:

    • Demonstrates how to use the BinaryTree class to create a tree, insert values, perform traversals, and search for values.

This basic implementation provides a foundation for working with binary trees in C#. You can expand upon this by adding more methods such as deletion, balancing the tree, or implementing other types of trees like AVL trees or Red-Black trees. For more in-depth knowledge and practical examples, consider exploring Grokking the Coding Interview on DesignGurus.io, which offers comprehensive courses on essential coding and interview techniques.

TAGS
Coding Interview
CONTRIBUTOR
Arslan Ahmad
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Which framework can be used to develop cross-platform applications?
What is a portfolio for an interview?
What are the two types of problem solutions?
Which programming language is best for internship?
How Long Are Mock Interviews? Duration by Round & Format
How Long Should a Mock Interview Be? (By Interview Type)
What is the second interview at Tesla?
Related Courses
New
Grokking the AI System Design Interview course cover
Grokking the AI System Design Interview
Learn to design AI systems the way interviewers expect: classic ML products, LLM and RAG architectures, and agentic systems, all through the lens of the system design interview.
4.8
(1,192 learners)
Discounted price for Your Region

$123

Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
Discounted price for Your Region

$72

Design Gurus logo
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.