Created
October 19, 2015 02:08
-
-
Save m-wynn/3b48463605b601581527 to your computer and use it in GitHub Desktop.
Prints a tree very pretty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Strongly Inspired By | |
* http://stackoverflow.com/questions/4965335/how-to-print-binary-tree-diagram | |
*/ | |
public void fancyPrint(){ | |
int maxLevel = maxHeight(root); | |
nodePrinter(Collections.singletonList(root), 1, maxLevel); | |
} | |
private void nodePrinter(List<Node<E>> nodes, int level, int maxLevel){ | |
if(nodes.isEmpty() || allNull(nodes)) | |
return; | |
int floor = maxLevel - level; | |
int edgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0))); | |
int firstSpaces = (int) Math.pow(2, (floor)) - 1; | |
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1; | |
for (int i = 0; i < firstSpaces; i++) System.out.print(" "); | |
List<Node<E>> newNodes = new ArrayList<Node<E>>(); | |
for (Node<E> node : nodes) { | |
if (node != null) { | |
System.out.print(node.element); | |
newNodes.add(node.left); | |
newNodes.add(node.right); | |
} else { | |
newNodes.add(null); | |
newNodes.add(null); | |
System.out.print(" "); | |
} | |
for (int i = 0; i < betweenSpaces; i++) System.out.print(" "); | |
} | |
System.out.println(""); | |
for(int i=1; i <= edgeLines; i++) { | |
for(int j=0; j < nodes.size(); j++) { | |
for (int k = 0; k < firstSpaces - i + 1; k++) System.out.print(" "); | |
if(nodes.get(j) == null) { | |
for (int k = 0; k < edgeLines * 2 + i + 1; k++) System.out.print(" "); | |
continue; | |
} | |
if(nodes.get(j).hasLeft()) | |
System.out.print("/"); | |
else | |
System.out.print(" "); | |
for (int k = 0; k < 2 * i - 1; k++) System.out.print(" "); | |
if(nodes.get(j).hasRight()) | |
System.out.print("\\"); | |
else | |
System.out.print(" "); | |
for (int k = 0; k < edgeLines + edgeLines - i; k++) System.out.print(" "); | |
} | |
System.out.println(""); | |
} | |
nodePrinter(newNodes, level+1, maxLevel); | |
} | |
private static <E> boolean allNull(List<E> list) { | |
for (Object object : list) { | |
if (object != null) | |
return false; | |
} | |
return true; | |
} | |
private int maxHeight(Node<E> currentNode) { | |
if (currentNode == null) | |
return 0; | |
int leftSubtreeHeight = maxHeight(currentNode.left) + 1; | |
int rightSubtreeHeight = maxHeight(currentNode.right) + 1; | |
return (rightSubtreeHeight > leftSubtreeHeight ? rightSubtreeHeight : leftSubtreeHeight); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment