title: Printing binary tree to standard output Java
body: <p>I'm implementing a red/black tree in Java and to verify if my tree is correct and to make debugging easier i simply copy/pasted a method that prints out the tree to standard output.</p>
  
  <p>For an input sequence of: <code>29, 42, 23, 47, 11, 4</code><br>
  the method would print out:</p>
  
  <p><img src="https://i.stack.imgur.com/2wXey.png" alt="enter image description here"></p>
  
  <p>With a little imagination this is in fact a red/black tree, just not with edges between the nodes.<br>
  42 is the black root with a right black child 47 and a left red child 23 (red nodes are surrounded by &lt; and >), etc.</p>
  
  <p>This is just fine for smaller trees but becomes a little complicated for larger trees.<br>
  Right now the root is to the left and the tree expands to the right. 
  I was wondering if there are any readily available methods that print out such a tree by printing the root first, and expanding the tree downwards?</p>
  
  <p>Like so:<br>
  <img src="https://i.stack.imgur.com/a7Clk.png" alt="enter image description here"></p>
  
  <p>Or if there is not such a method readily available, how could i change the current method so it prints like the second image?</p>
  
  <p>This is the current method: </p>
  
  <pre><code>private static void printHelper(Node n, int indent) {
  
      if (n.getRight() != null) {
          printHelper(n.getRight(), indent + INDENT_STEP);
      }
  
      for (int i = 0; i &lt; indent; i++) {
          System.out.print(" ");
      }
  
      if (n.getColor() == BLACK) {
          System.out.println(n.getValue());
      } else {
          System.out.println("&lt;" + n.getValue() + "&gt;");
      }
  
      if (n.getLeft() != null) {
          printHelper(n.getLeft(), indent + INDENT_STEP);
      }
  }
  </code></pre>
  
  <p>And is being called with the root of the tree as node and 0 as indent (and <code>INDENT_STEP</code> is 4).</p>
  
  <p><strong>EDIT</strong>: Now that i think of it this is not a specific problem to red/black trees. I'm thus removing the red/black from the title and i replace it with binary tree.</p>