Binary Tree Traversals in C#

Lesson Overview

Get ready to embark on an exciting journey through the woods — the binary woods, that is. One example of such a task is covering the concept of Binary Tree Traversals. A Binary Tree is a type of data structure in which each node has at most two children, referred to as the left child and the right child. Traversing such a structure involves visiting each node in a specific order — and C#, with its strong typing and object-oriented features, makes this task quite manageable.

Binary Tree Definition

Before diving deeper into the traversals, let's define a simple structure for a binary tree node in C#. Each node in a binary tree will have a value, a reference to its left child, and a reference to its right child.

Here’s how you can define a basic binary tree node class in C#:

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

    public TreeNode(int value)
    {
        this.Value = value;
        this.Left = null;
        this.Right = null;
    }

    public TreeNode(int value, TreeNode left, TreeNode right)
    {
        this.Value = value;
        this.Left = left;
        this.Right = right;
    }
}

This TreeNode class initializes a node with a given value and optional left and right children, which default to null if not provided. This structure will serve as the foundation for implementing the different binary tree traversal methods.

Quick Example

We have three primary ways to traverse a binary tree: Inorder (Left, Root, Right), Preorder (Root, Left, Right), and Postorder (Left, Right, Root). One way is to use recursive Inorder traversal. If a tree is not empty, we will first recursively traverse the left subtree, then visit the root, and finally, recursively traverse the right subtree. In this way, we can explore every corner of our binary landscape.

The solution might look like this:

using System;
using System.Collections.Generic;

public class BinaryTreeTraversal
{
    public static List<int> InorderTraversal(TreeNode root)
    {
        List<int> result = new List<int>();
        InorderHelper(root, result);
        return result;
    }

    private static void InorderHelper(TreeNode node, List<int> result)
    {
        if (node == null)
        {
            return;
        }
        InorderHelper(node.Left, result);
        result.Add(node.Value);
        InorderHelper(node.Right, result);
    }

    public static void Main(string[] args)
    {
        TreeNode root = new TreeNode(1, null, new TreeNode(2, new TreeNode(3), null));
        Console.WriteLine(string.Join(", ", InorderTraversal(root)));  // Output: 1, 3, 2
    }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal