2010-10-21 11 views
5

Voglio implementare una struttura ad albero che abbia profondità fissa, vale a dire quando si aggiungono figli ai nodi del leef, l'intera struttura ad albero dovrebbe "spostarsi". Ciò significa anche che diverse radici possono esistere contemporaneamente. Vedere l'esempio sotto: alt text In questo esempio, i nodi verdi vengono aggiunti nell'iterazione 1, eliminando il nodo superiore (grigio) e rendendo i due nodi blu nei nodi radice K = 0 e Iteration 1.Correggere l'albero di profondità in Python

Come faccio a implementare questo?

risposta

2

Memorizza ogni nodo con un riferimento al relativo genitore. Quando aggiungi un nodo ad esso come un bambino, apri i genitori (dal nodo che viene aggiunto a) ed elimina il terzo dopo aver impostato il riferimento principale in tutti i suoi figli su None. Quindi aggiungi i figli del nodo eliminato alla tua lista di alberi.

class Node(object): 

    depth = 4 

    def __init__(self, parent, contents): 
     self.parent = parent 
     self.contents = contents 
     self.children = [] 


def create_node(trees, parent, contents): 
    """Adds a leaf to a specified node in the set of trees. 

    Note that it has to have access to the container that holds all of the trees so 
    that it can delete the appropriate parent node and add its children as independent 
    trees. Passing it in seems a little ugly. The container of trees could be a class 
    with this as a method or you could use a global list. Or something completely 
    different. The important thing is that if you don't delete every reference to the 
    old root, you'll leak memory. 
    """ 
    parent.children.append(Node(parent, contents)) 

    i = 0: 
    L = Node.depth - 1 
    while i < L: 
     parent = parent.parent 
     if not parent: 
      break 
     i += 1 
    else: 
     for node in parent.children: 
      node.parent = None 
     trees.extend(parent.children) 
     i = trees.find(parent) 
     del trees[i] 
+0

Questo è stato un po 'quello che stavo cercando. Grazie! – Theodor

Problemi correlati