title: print a binary tree on its side
body: <p>How can you print a binary tree on its side so the output looks like this?</p>
  
  <pre><code>   __/a
  __/  \b
    \   _/c
     \_/ \d
       \e
  </code></pre>
  
  <p><sub>(Prettier ascii-art welcome)</sub></p>
  
  <p>Here's some code that doesn't quite work:</p>
  
  <pre><code>def print_tree(tree):
      def emit(node,prefix):
          if "sequence" in node:
              print "%s%s"%(prefix[:-1],node["name"])
          else:
              emit(node["left"],"%s_/ "%prefix.replace("/ "," /")[:-1].replace("_"," "))
              emit(node["right"],"%s \\ "%prefix.replace("\\ "," \\")[:-1])
      emit(tree,"")    
  </code></pre>
  
  <p>Which outputs this:</p>
  
  <pre><code>      _/hg19
      _/ \rheMac2
    _/ \mm9
    /\_/bosTau4
    /  \_/canFam2
  _/     \pteVam1
   \_/loxAfr3
     \dasNov2
  </code></pre>
  
  <p><em>Scope creep</em>: it would be excellent if you could pass in a function that will return the string to print of any node; in this way, I can sometimes print information about non-leave nodes too.  So whether a node has anything to print is controlled by the function passed in as a parameter.</p>
  
  <p>Here's some test-data in JSON:</p>
  
  <pre><code>{
      "left": {
          "left": {
              "left": {
                  "left": {
                      "name": "hg19", 
                      "sequence": 0
                  }, 
                  "right": {
                      "name": "rheMac2", 
                      "sequence": 1
                  }
              }, 
              "right": {
                  "name": "mm9", 
                  "sequence": 2
              }
          }, 
          "right": {
              "left": {
                  "name": "bosTau4", 
                  "sequence": 3
              }, 
              "right": {
                  "left": {
                      "name": "canFam2", 
                      "sequence": 4
                  }, 
                  "right": {
                      "name": "pteVam1", 
                      "sequence": 5
                  }
              }
          }
      }, 
      "right": {
          "left": {
              "name": "loxAfr3", 
              "sequence": 6
          }, 
          "right": {
              "name": "dasNov2", 
              "sequence": 7
          }
      }
  }
  </code></pre>