Thursday, 22 August 2013

Printing out a binary tree with increased leading white spaces per level

Printing out a binary tree with increased leading white spaces per level

Lets say I have the tree a binary tree
0
1 2
3 4 5 6
7 8
At the moment I am printing them out traversing my tree in java (recursively)
private static void preorderTraverseTree(BinaryTree<Integer> tree,
Position<Integer> root) {
if (root != null) {
if (tree.hasLeft(root)) {
if(External(tree, tree.left(root))){
printQ(tree.left(root), true);
}
//if it not an external node, External(tree, Pos<Integer>)
else if(!External(tree, tree.left(root))){
//System.out.println(counter(3) + )
printR(tree.left(root), true);
//System.out.println("external");
}
preorderTraverseTree(tree, tree.left(root));
}
}
}
This is one part of the recursive the other part is the same but just for
the right roots rather than the left.
My printQ and R are as follow
private static void printQ(Position<Integer> result, boolean yes) {
if (yes) {
System.out.println("Y->Q" + result.element() + ":");
} else {
System.out.println("N->Q" + result.element() + ":");
}
}
private static void printR(Position<Integer> result, boolean yes) {
if (yes) {
System.out.println("Y->R" + result.element());
} else {
System.out.println("N->R" + result.element());
}
}
This just prints out the element at the node of which has been given in
and a statement true or false for Y and N to appear.
This prints out the following
Q0:
Y->Q1:
Y->Q3:
Y->R7
N->R8
N->R4
N->Q2:
Y->R5
N->R6 (R denotes an external node)
However my question is how can I get it to have leading white spaces to
denote the children for each node? Like so,
Q0:
Y->Q1:
Y->Q3:
Y->R7
N->R8
N->R4
N->Q3:
Y->R2
N->R8
Basically 3 white spaces per level, so 0 for the first, 6 for the second 9
for third and so on. Apart from Q0 which is the root of the tree, I wanted
this to have no white spaces.
EDIT: The children from the original ROOT are 1 and 2, so these should
have the same amount of whitespace before them
Things I have tried so far
Firstly I implemented a counter that counted 3 extra white spaces per
recursion, however I soon found that to be silly since it just printed
them all like a staircase.
I tried setting a boolean flag and making it add white space beforehand
dependent on whether the flag was true or false. Had no luck there
either...
Does anyone have an idea of how I could go about adding this in?
Cheers in advance,
Jim
PS: Post for any clarifications below

No comments:

Post a Comment