Dynamic Variable Naming for tree[Python]
<p>I have made a tree structure for preorder traversal.
And I can manually name all the variables.</p>

<p>Is there a way to make a variable. I need a tree structure as follows:</p>

<pre><code>        0
   1        2 
 3    4     5   6
7 8 9 10 11 12 13 14
...
</code></pre>

<p>and so on.</p>

<pre><code>import time
class Node: 
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def fetch(root):
    if root is None:
        return
    x = []
    x.append(root)
    while(len(x) &gt; 0):      
        node = x.pop()
        print (node.data)
        if node.right is not None:
            x.append(node.right)
        if node.left is not None:
            x.append(node.left)

root = Node(0)

root.left = Node(1)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(5)
root.right.right =Node(6)
root.left.left.left=Node(7)
root.left.left.right=Node(8)

start_time=time.time()
fetch(root)
end_time=time.time()

print ("Object time :"+str(end_time-start_time))
</code></pre>

<p>I want to have 1M nodes. Which is not possible to type in manually. Could someone please suggest a function or way of doing it?
Thanks!</p>

<p>It seems that you are going from left-to-right on the tree. If we represent the path in binary, the leftmost branch (on the forth layer down) as <code>0000</code> (<code>.left.left.left.left</code>) then then next number would be <code>0001</code> (<code>.left.left.left.right</code>). Then it would be <code>0010</code> (<code>.left.left.right.left</code>). This could be implemented like this:</p>

<pre><code>root = Node(0)
level = 1
branch = 0
for n in range(1, 1000001):
    *current_branch, final = '{:0{}b}'.format(branch, level)
    # Makes current_branch the binary equivalent of &lt;branch&gt;
    # padded with '0's to be &lt;level&gt; length
    # and final is the last digit
    place = root
    for direction in current_branch: # Iteratively gets the correct path down the tree
        # direction = ('left', 'right')[int(direction)]  # '0' -&gt; 'left;' '1' -&gt; 'right'
        place = getattr(place, ('left', 'right')[int(direction)])  
    setattr(place, final, Node(n))  # Sets the final direction to the right Node
    branch += 1
    if branch &gt;= 2 ** level:  # If the branch is to the right of the right-most branch
        branch = 0
        level += 1  # Reset the branch and go a level deeper
</code></pre>

python variables dynamic tree traversal