public static void ToArray(Tree tree, TreeStruct[] array, bool isLeft, int parentIndex) { if (parentIndex != -1) { if (isLeft) { array[parentIndex].Left = curIndex + 1; } else { array[parentIndex].Right = curIndex + 1; } } parentIndex = curIndex; array[curIndex++] = new TreeStruct(tree.key); if (tree.left != null) { ToArray(tree.left, array, true, parentIndex); } if (tree.right != null) { ToArray(tree.right, array, false, parentIndex); } }
static void Main(string[] args) { var sr = new StreamReader("input.txt"); var sw = new StreamWriter("output.txt"); int n = int.Parse(sr.ReadLine()); for (int i = 0; i < n; i++) { args = sr.ReadLine().Split(); tree = Tree.Insert(tree, int.Parse(args[0])); } //Tree.Print(tree); tree = Tree.InsertWithBalance(tree, int.Parse(sr.ReadLine())); //tree = Tree.Balance(tree); var numElements = Tree.GetElementsNum(tree); var array = new TreeStruct[numElements]; Tree.ToArray(tree, array); //Console.WriteLine(); //Tree.Print(tree); sw.WriteLine(numElements); for (int i = 0; i < numElements; i++) { sw.WriteLine(array[i].ToString()); } sr.Close(); sw.Close(); }