3
\$\begingroup\$

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;
    }
}

How can the printTree method be improved?

\$\endgroup\$
  • 6
    \$\begingroup\$ Welcome to Code Review! Does this compile? What's 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 for NoteRB, or even a full example so that reviewers can run it too. \$\endgroup\$ – ferada Sep 4 '18 at 23:07
  • 2
    \$\begingroup\$ I've updated the code with complete class. Thanks. \$\endgroup\$ – DAme Sep 20 '18 at 9:34
  • \$\begingroup\$ @DAme is this currently working? If so could you provide an example? I tried but to no success \$\endgroup\$ – dustytrash Apr 8 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.