For the pretty print method of my BST class, we were told by our lecturer for the tree:
bst.put(7, 7); // _7_
bst.put(8, 8); // / \
bst.put(3, 3); // _3_ 8
bst.put(1, 1); // / \
bst.put(2, 2); // 1 6
bst.put(6, 6); // \ /
bst.put(4, 4); // 2 4
bst.put(5, 5); // \
// 5
The code must print the tree as so:
"-7\n" +
" |-3\n" +
" | |-1\n" +
" | | |-null\n" +
" | | -2\n" +
" | | |-null\n" +
" | | -null\n" +
" | -6\n" +
" | |-4\n" +
" | | |-null\n" +
" | | -5\n" +
" | | |-null\n" +
" | | -null\n" +
" | -null\n" +
" -8\n" +
" |-null\n" +
" -null\n";
I have got my code to print out the tree almost perfect to what the lecturer as specified using recursion, although I cannot find a way to print the white spaces as he specified. I understand it is a problem with only printing the characters on any right sub tree, but im unsure of a way to correctly print the spaces.
Here is how my code prints:
-7
|-3
| |-1
| | |-null
| |-2
| | |-null
| |-null
|-6
| |-4
| | |-null
| |-5
| | |-null
| |-null
|-null
-8
|-null
-null
As you can see for the right sub tree nodes there is no prefixxed spacing, and any attempt to prefix a space for the right sub tree nodes, has only altered the format of the tree.
Here is my code, any help would be deeply gratified
public String prettyPrintKeys() {
String output = "";
int indent = 0;
output = prettyPrint(root, indent);
System.out.print(output);
return output;
}
private String prettyPrint(Node x, int indent){
String output = "";
for(int i=0; i<indent; i++){
output = output + " |";
}
if(x == null){
return output = output + "-null\n";
}
indent++;
output = output + "-" + x.key + "\n" + prettyPrint(x.left, indent);
indent--;
output = output + prettyPrint(x.right, indent);
return output;
}