Last active
March 29, 2021 11:31
-
-
Save SauliusSun/9572698 to your computer and use it in GitHub Desktop.
Recursion example in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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