2016-08-30 104 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