using System; using System.Linq; using System.Collections.Generic; using System.Collections; public class Test { public static void Main() { int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, 12, 14, 13, 10, 11 }; Dictionary layers = new Dictionary(); int n = arr.Length, nodesInRow = 1, currentNodeInRow = -1, rowCenter, currentNodeLayer = 0, maxLayer = -1; for (int i = 0; i < n; i++) { if (currentNodeInRow == nodesInRow - 1) { nodesInRow *= 2; currentNodeInRow = 0; } else currentNodeInRow++; if (i == 0) { layers.Add(0, 0); // Special case continue; } rowCenter = nodesInRow / 2 - 1; if (currentNodeInRow <= rowCenter) currentNodeLayer = currentNodeInRow; else currentNodeLayer = nodesInRow - currentNodeInRow - 1; if (currentNodeLayer > maxLayer) maxLayer = currentNodeLayer; layers.Add(i, currentNodeLayer); // Console.WriteLine("{0} => {1}", i, currentNodeLayer); } for (int i = 0; i <= maxLayer; i++) { Console.Write("Layer {0}:", i + 1); foreach (var x in layers.Where((p) => p.Value == i)) if (arr[x.Key] != -1) Console.Write("{0} ", arr[x.Key]); Console.WriteLine(); } } }