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

あなたはツリーの左から右に向かっているようです。パスを2進数で表すと、0000.left.left.left.left)のように左端のブランチ(4番目のレイヤーが下にある)は、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 
関連する問題