//determines the height of a binary tree private static int GetHeight(IPrintableBinaryNode theGuy) { if (theGuy == null) { return(0); } return(1 + Math.Max(GetHeight(theGuy.GetLeft()), GetHeight(theGuy.GetRight()))); }
//prints tree to char[][] starting at pos private static void PrintToArray(char[,] screen, IPrintableBinaryNode node, int height, Coord pos, int dataLength) { if (node == null) { return; } //print node data string data = node.GetString(); InsertStringToCharArrayCentered(screen, pos, data); //should traverse if (height == 1) { return; } //trust the math int lastWidth = GetWidth(height - 1, dataLength); int numOfDashes = (lastWidth - 1) / 2 - ((dataLength - 1) / 2 - 1); int offset = (dataLength - 1) / 2; //printing the pretty for (int i = 1; i <= numOfDashes; i++) { char printL = i == numOfDashes ? LeftDownPlaceholder : SideWaysPlaceholder; // character to be printed char printR = i == numOfDashes ? RightDownPlaceholder : SideWaysPlaceholder; // character to be printed offset += 1; if (node.GetLeft() != null) { InsertStringToCharArray(screen, pos.Add(-offset, 0), printL); // PRINT!! } if (node.GetRight() != null) { InsertStringToCharArray(screen, pos.Add(offset, 0), printR); // PRINT!! } } //recourse for each branch with position at the end of each branch +1 in the y PrintToArray(screen, node.GetLeft(), height - 1, pos.Add(-offset, 1), dataLength); PrintToArray(screen, node.GetRight(), height - 1, pos.Add(offset, 1), dataLength); }