using System; class BinaryTree { public BinaryTree Left { get; } public BinaryTree Right { get; } public T Value { get; } public BinaryTree(T value, BinaryTree left = null, BinaryTree right = null) { this.Value = value; this.Left = left; this.Right = right; } public BinaryTree Map(Func f) { return new BinaryTree(f(this.Value), this.Left?.Map(f), this.Right?.Map(f)); } public override string ToString() { var sb = new System.Text.StringBuilder(); this.ToString(sb, 0); return sb.ToString(); } private void ToString(System.Text.StringBuilder sb, int depth) { sb.Append(new string('\t', depth)); sb.AppendLine(this.Value?.ToString()); this.Left?.ToString(sb, depth + 1); this.Right?.ToString(sb, depth + 1); } } static class Program { static void Main() { var b = new BinaryTree(6, new BinaryTree(5), new BinaryTree(7)); BinaryTree b2 = b.Map(x => x * 0.5); Console.WriteLine(b); Console.WriteLine(b2); } }