2016-08-30 61 views
-1

我为前序遍历做了一个树结构。 我可以手动命名所有变量。树的动态变量命名[Python]

有没有办法让一个变量。我需要一个树形结构如下:

 0 
    1  2 
3 4  5 6 
7 8 9 10 11 12 13 14 
... 

等等。

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) > 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)) 

我想拥有1M个节点。无法手动输入。有人可以建议一个功能或做法吗? 谢谢!

回答

0

看来你是打算由左到右的树。如果我们用二进制表示的路径,最左边的分支(在第四层下)为0000.left.left.left.left),然后再下一个数字是0001.left.left.left.right)。那么这将是0010.left.left.right.left)。这可以实现这样的:

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 <branch> 
    # padded with '0's to be <level> 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' -> 'left;' '1' -> '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 >= 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