title: Edgelist from a binary tree
body: <p>I'd like to make a pretty plot of my binary tree. </p>
  
  <p>Here's my custom BinaryTree class:</p>
  
  <pre><code>class BinaryTree():
  
     def __init__(self, data):
        self.data = data
        self.right = None
        self.left = None
  </code></pre>
  
  <p>Now, in order to plot this graph I'll use the networkx library and so I need to convert my graph to a networkx object and then plot it using graphviz. The problem is the <strong>edge list</strong>: in order to build my new object, I need the edges.</p>
  
  <p>For example given a binary tree like in the following figure.
  <img src="https://i.stack.imgur.com/5bQEY.png" alt="enter image description here"></p>
  
  <p>I need to retrieve the edge list. Would be something like this:</p>
  
  <pre><code>[(0,1),(0,2),(2,3),(2,4)]
  </code></pre>
  
  <p>Notice that in my case I don't have id on node. And so how can I do this?
  I believe it might be some recursive function taking account on the depth but I'm having some difficulties so a little help is appreciated. ;)</p>
  
  <p>EDIT</p>
  
  <p>Thanks for the answers. But I found a solution by myself that works well..:P
  Here it is:</p>
  
  <pre><code>def edgelist(node, output, id=0):
  
      if node is None or isinstance(node, bt.Leaf):
           return output
  
      if node.left:
           output.append((id, id*2+1))
  
      if node.right:
           output.append((id, id*2+2))
  
      edgelist(node.left, output, id*2+1)
      edgelist(node.right, output, id*2+2)
  
      return output
  </code></pre>