示例#1
0
    def find(self, value, print_path=False):
        node = Node(value)
        
        if node not in self.parents:
            ''' If the given value is not in the tree yet,
            then create it.'''
            
            self.parents[node] = node.parent
            return node
        
        ''' This is a critical part in this method.
        from the given node, travelling back to its ancestor.
        '''
        path = [node]
        root = self.parents[node]
        while root != path[-1]:
            path.append(root)
            root = self.parents[root]
            
        ''' This part handles the path-compression,
        changing the parent of the nodes which are in the path to root .'''
        for ancestor in path:
            self.parents[ancestor] = root
        
        if print_path:
            path_printer(path)

        # return the root of the set
        return root
示例#2
0
 def find(self, value, print_path=False):
     node = Node(value)
     
     if node not in self.parents:
         ''' If the given value is not in the tree yet,
         then create it.'''
         
         self.parents[node] = node.parent
         return node
     
     ''' This is a critical part in this method.
     from the given node, travelling back to its ancestor.
     '''
     path = [node]
     root = self.parents[node]
     while root != path[-1]:
         path.append(root)
         root = self.parents[root]
         
     path_printer(path)
     return root