Study backup for exams – understand recursion with real examples.
Recursion means that a method calls itself to solve a smaller part of a problem.
void Recurse(int x)
{
if (x == 0) return; // Base case
Recurse(x - 1); // Recursive call
}
Recursively collects all files from a directory and its subdirectories.
List<FileEntry> Scan(string path)
{
var list = new List<FileEntry>();
foreach (var file in Directory.GetFiles(path))
list.Add(new FileEntry { FullPath = file });
foreach (var dir in Directory.GetDirectories(path))
list.AddRange(Scan(dir)); // Recursive call
return list;
}
Convert flat path strings into a nested tree structure.
TreeNode Build(List<string> paths)
{
var root = new TreeNode { Name = "ROOT" };
foreach (var p in paths)
{
var parts = p.Split('\\');
var curr = root;
foreach (var part in parts)
{
var next = curr.Children.FirstOrDefault(c => c.Name == part);
if (next == null)
curr.Children.Add(next = new TreeNode { Name = part });
curr = next;
}
}
return root;
}
Recursively prints a directory tree with indentation.
void Print(TreeNode node, string indent = "")
{
Console.WriteLine(indent + node.Name);
foreach (var child in node.Children)
Print(child, indent + " "); // Recursive call
}