representing a tree as a list in python
<p>I'm learning python and I'm curious about how people choose to store (binary) trees in python. </p>

<p>Is there something wrong in storing the nodes of the tree as a list in python? something like:</p>

<pre><code>[0,1,2,3,4,5,6,7,8]
</code></pre>

<p>where the 0'th position is 0 by default, 1 is the root, and for each position (i), the 2i and 2i+1 positions are the children. When no child is present, we just have a 'None' in that position. </p>

<p>I've read a couple of books/notes where they represent a tree using a list of lists, or something more complicated than just a simple list like this, and I was wondering if there's something inherently wrong in how i'm looking at it?</p>

<p>There's nothing wrong with storing a binary tree as a list the way you're doing - it's the same idea as storing it as a flat array in a language like C or Java. Accessing the parent of a given node is very fast, and finding the children is also pretty efficient.</p>

<p>I suppose a lot of examples and tutorials will prefer to use a representation that's 'really tree shaped' (list of lists or objects) - it might be a bit more intuitive to explain.</p>

python binary-tree