When you're working with trees one of the most useful methods to implement is a clear way to print them, the following is my solution to print a tree in Java:
class BlackRedBST{
public static final NodeRB NILL = null;
public static final boolean RED = true;
public static final boolean BLACK = false;
NodeRB root;
public BlackRedBST () {
root = NILL;
}
public void printTree(NodeRB tree, String indent, boolean print_leaf) {
if(tree == NILL) {
System.out.print((print_leaf?indent+" |-+*\n":""));
} else {
indent += " ";
if(tree.p == NILL || tree.p == null) {
printTree(tree.right, indent + " ", print_leaf);
System.out.print(indent + "+" + tree.value + "\n");
printTree(tree.left, indent + " ", print_leaf);
}else if(tree.p.right==tree) {
printTree(tree.right, indent + " ", print_leaf);
System.out.print(indent + "|+" + tree.value + "\n");
printTree(tree.left, indent + "|", print_leaf);
}
else {
printTree(tree.right, indent + "|", print_leaf);
System.out.print(indent + "|+" + tree.value + "\n");
printTree(tree.left, indent + " ", print_leaf);
}
}
}
}
To be clear in the following the NodeRB class:
class NodeRB{
int value;
NodeRB p;
NodeRB left;
NodeRB right;
boolean color;
int level;
public NodeRB(int v) {
value = v;
color = BlackRedBST.RED;
left = BlackRedBST.NILL;
right = BlackRedBST.NILL;
level = 1;
}
}
To complete the code, here is a class with main to test my code:
public class PreattyPrintTree {
public static void main(String[] args) {
BlackRedBST bst = new BlackRedBST();
// this is a sample, but a method to add the nodes should be write
bst.root = new NodeRB(1);
bst.root.left = new NodeRB(2);
bst.root.left.level = 2;
bst.root.left.p=bst.root;
bst.root.right = new NodeRB(3);
bst.root.right.p = bst.root;
bst.root.right.level = 2;
bst.printTree(bst.root, "\t", true);
}
}
An output sample, with three nodes and print of leaf enabled:
|-+*
|+3
| |-+*
+1
| |-+*
|+2
|-+*
How can the printTree method be improved?
NILL
? Please always make sure that any code is working as far as you know before posting it here, otherwise it's considered off-topic. Also it wouldn't hurt to include a bit more context, perhaps the class definition forNoteRB
, or even a full example so that reviewers can run it too. \$\endgroup\$p
is never filled in. Could you provide an example of a tree to output? \$\endgroup\$