Skip to content

Instantly share code, notes, and snippets.

@SauliusSun
Last active March 29, 2021 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SauliusSun/9572698 to your computer and use it in GitHub Desktop.
Save SauliusSun/9572698 to your computer and use it in GitHub Desktop.
Recursion example in C#
using System;
using System.Collections.Generic;
namespace RecursionExample
{
internal class RecursionExample
{
static void Main()
{
var items = new List<string> { "Node1", "Node2", "Node3" };
string output = BuildRecursionTree("", items, 0);
// Result: Node1 <- Node2 <- Node3 <-.
Console.Write(output);
}
static string BuildRecursionTree(string value, IList<string> items, int index)
{
// "index" variable value checking helps call recursive function finite number of times.
if (items.Count == index)
{
return value;
}
// Add node.
value += " " + items[index] + " <-";
// Actual recursion: call function itself once more time.
return BuildRecursionTree(value, items, index + 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment