Recursive tree build method.

@param msg Minimum spanning graph
@param cur Current node
@param parent Parent node
@param nodes Nodes array to fill - must be preinitialized with nulls!
@return Tree of nodes
484766
protected N buildTree(int[] msg, int cur, int parent, ArrayList<N> nodes) {
    // Count the number of children:
    int c = 0;
    for(int i = 1; i < msg.length; i += 2) {
      if((msg[i - 1] == cur && msg[i] != parent) || (msg[i] == cur && msg[i - 1] != parent)) {
        c++;
      }
    }
    // Build children:
    List<N> children = Collections.emptyList();
    if(c > 0) {
      children = new ArrayList<>(c);
      for(int i = 1; i < msg.length; i += 2) {
        if(msg[i - 1] == cur && msg[i] != parent) {
          children.add(buildTree(msg, msg[i], cur, nodes));
        }
        else if(msg[i] == cur && msg[i - 1] != parent) {
          children.add(buildTree(msg, msg[i - 1], cur, nodes));
        }
      }
    }
    N node = makeNode(cur, children);
    nodes.set(cur, node);
    return node;
  }
147725
def root_and_children_to_graph(self,root):
     """"""
     g = Graph()
     g.add_node(root)
     edges = []
     edges += self.get_node_edges(root,"outgoing")
     for c in self.get_children(root):
           g.add_node(c)
           edges += self.get_node_edges(c,"outgoing")
     for e in edges: g.add_edge(e)
     return g
736502
def find_minimum_spanning_tree(graph):
    
    mst = []

    if graph.num_nodes() == 0:
        return mst
    if graph.num_edges() == 0:
        return mst

    connected_components = get_connected_components(graph)
    if len(connected_components) > 1:
        raise DisconnectedGraphError

    edge_list = kruskal_mst(graph)

    return edge_list
290049
private static SoyMsgSelectPart buildMsgPartForSelect(
      MsgSelectNode msgSelectNode, MsgNode msgNode) {

    // This is the list of the cases.
    ImmutableList.Builder<SoyMsgPart.Case<String>> selectCases = ImmutableList.builder();

    for (CaseOrDefaultNode child : msgSelectNode.getChildren()) {
      ImmutableList<SoyMsgPart> caseMsgParts =
          buildMsgPartsForChildren((MsgBlockNode) child, msgNode);
      String caseValue;
      if (child instanceof MsgSelectCaseNode) {
        caseValue = ((MsgSelectCaseNode) child).getCaseValue();
      } else if (child instanceof MsgSelectDefaultNode) {
        caseValue = null;
      } else {
        throw new AssertionError("Unidentified node under a select node.");
      }
      selectCases.add(SoyMsgPart.Case.create(caseValue, caseMsgParts));
    }

    return new SoyMsgSelectPart(msgNode.getSelectVarName(msgSelectNode), selectCases.build());
  }
310864
def disjoint_mst(X, num_spanning_trees=3, metric='euclidean'):
  ''''''
  D = pairwise_distances(X, metric=metric)
  if metric == 'precomputed':
    D = D.copy()
  mst = minimum_spanning_tree(D)
  W = mst.copy()
  for i in range(1, num_spanning_trees):
    ii,jj = mst.nonzero()
    D[ii,jj] = np.inf
    D[jj,ii] = np.inf
    mst = minimum_spanning_tree(D)
    W = W + mst
  # MSTs are all one-sided, so we symmetrize here
  return Graph.from_adj_matrix(W + W.T)
1300523
public static STRtree geometriesToSRTree( List<Geometry> geometries ) {
        STRtree tree = new STRtree();
        for( Geometry geometry : geometries ) {
            tree.insert(geometry.getEnvelopeInternal(), geometry);
        }
        return tree;
    }
566148
private void buildSpanningTree(IAtomContainer atomContainer) {
        disconnected = false;
        molecule = atomContainer;

        totalVertexCount = atomContainer.getAtomCount();
        totalEdgeCount = atomContainer.getBondCount();

        sptSize = 0;
        edrSize = 0;
        fastFindInit(totalVertexCount);
        for (int i = 0; i < totalVertexCount; i++) {
            (atomContainer.getAtom(i)).setProperty(ATOM_NUMBER, Integer.toString(i + 1));
        }
        IBond bond;
        int vertex1, vertex2;
        bondsInTree = new boolean[totalEdgeCount];

        for (int b = 0; b < totalEdgeCount; b++) {
            bondsInTree[b] = false;
            bond = atomContainer.getBond(b);
            vertex1 = Integer.parseInt((bond.getBegin()).getProperty(ATOM_NUMBER).toString());
            vertex2 = Integer.parseInt((bond.getEnd()).getProperty(ATOM_NUMBER).toString());
            //this below is a little bit  slower
            //v1 = atomContainer.indexOf(bond.getAtomAt(0))+1;
            //v2 = atomContainer.indexOf(bond.getAtomAt(1))+1;
            if (fastfind(vertex1, vertex2, true)) {
                bondsInTree[b] = true;
                sptSize++;
                //logger.debug("ST : includes bond between atoms "+v1+","+v2);
            }
            if (sptSize >= (totalVertexCount - 1)) break;

        }
        // if atomcontainer is connected then the number of bonds in the spanning tree = (No atoms-1)
        //i.e.  edgesRings = new Bond[E-V+1];
        //but to hold all bonds if atomContainer was disconnected then  edgesRings = new Bond[E-sptSize];
        if (sptSize != (totalVertexCount - 1)) disconnected = true;
        for (int b = 0; b < totalEdgeCount; b++)
            if (!bondsInTree[b]) {
                //			edgesRings[edrSize] = atomContainer.getBondAt(b);
                edrSize++;
            }
        cb = new int[edrSize][totalEdgeCount];
        for (int i = 0; i < edrSize; i++)
            for (int a = 0; a < totalEdgeCount; a++)
                cb[i][a] = 0;

        // remove ATOM_NUMBER props again
        for (IAtom atom : atomContainer.atoms())
            atom.removeProperty(ATOM_NUMBER);
    }
1072143
public static <T> T root(TreeDef.Parented<T> treeDef, T node) {
		T lastParent;
		T parent = node;
		do {
			lastParent = parent;
			parent = treeDef.parentOf(lastParent);
		} while (parent != null);
		return lastParent;
	}
247395
def add_spanning_tree(self, st):
        
        self.add_nodes(list(st.keys()))
        for each in st:
            if (st[each] is not None):
                self.add_edge((st[each], each))
1032150
def get_root_graph(self,root):
      """"""
      children = self.get_children(root)
      g = Graph()
      nodes = [root]+children
      for node in nodes: g.add_node(node)
      node_ids = [x.id for x in nodes]
      edges = [x for x in self._edges.values() if x.node1.id in node_ids and x.node2.id in node_ids]
      for e in edges: g.add_edge(e)
      return g
761472
function(node, parent){
    var debug = this.debug;

    if (!node) {
      var msg;
      if (parent) {
        msg = 'A child of ' + parent.type + ' (' + (parent.filename || 'Pug') + ':' + parent.line + ')';
      } else {
        msg = 'A top-level node';
      }
      msg += ' is ' + node + ', expected a Pug AST Node.';
      throw new TypeError(msg);
    }

    if (debug && node.debug !== false && node.type !== 'Block') {
      if (node.line) {
        var js = ';pug_debug_line = ' + node.line;
        if (node.filename) js += ';pug_debug_filename = ' + stringify(node.filename);
        this.buf.push(js + ';');
      }
    }

    if (!this['visit' + node.type]) {
      var msg;
      if (parent) {
        msg = 'A child of ' + parent.type
      } else {
        msg = 'A top-level node';
      }
      msg += ' (' + (node.filename || 'Pug') + ':' + node.line + ')'
           + ' is of type ' + node.type + ','
           + ' which is not supported by pug-code-gen.'
      switch (node.type) {
      case 'Filter':
        msg += ' Please use pug-filters to preprocess this AST.'
        break;
      case 'Extends':
      case 'Include':
      case 'NamedBlock':
      case 'FileReference': // unlikely but for the sake of completeness
        msg += ' Please use pug-linker to preprocess this AST.'
        break;
      }
      throw new TypeError(msg);
    }

    this.visitNode(node);
  }
115968
def _build_first_tree(self):
        """"""
        # Prim's algorithm
        neg_tau = -1.0 * abs(self.tau_matrix)
        X = {0}

        while len(X) != self.n_nodes:
            adj_set = set()
            for x in X:
                for k in range(self.n_nodes):
                    if k not in X and k != x:
                        adj_set.add((x, k))

            # find edge with maximum
            edge = sorted(adj_set, key=lambda e: neg_tau[e[0]][e[1]])[0]
            name, theta = Bivariate.select_copula(self.u_matrix[:, (edge[0], edge[1])])

            left, right = sorted([edge[0], edge[1]])
            new_edge = Edge(len(X) - 1, left, right, name, theta)
            new_edge.tau = self.tau_matrix[edge[0], edge[1]]
            self.edges.append(new_edge)
            X.add(edge[1])
457735
protected N buildSpanningTree(int dim, double[] mat, Layout layout) {
    assert (layout.edges == null || layout.edges.size() == 0);
    int[] iedges = PrimsMinimumSpanningTree.processDense(mat, new LowerTriangularAdapter(dim));
    int root = findOptimalRoot(iedges);

    // Convert edges:
    ArrayList<Edge> edges = new ArrayList<>(iedges.length >> 1);
    for(int i = 1; i < iedges.length; i += 2) {
      edges.add(new Edge(iedges[i - 1], iedges[i]));
    }
    layout.edges = edges;

    // Prefill nodes array with nulls.
    ArrayList<N> nodes = new ArrayList<>(dim);
    for(int i = 0; i < dim; i++) {
      nodes.add(null);
    }
    layout.nodes = nodes;
    N rootnode = buildTree(iedges, root, -1, nodes);

    return rootnode;
  }
1355618
def depth_first_search_with_parent_data(graph, root_node = None, adjacency_lists = None):
    """"""
    ordering = []
    parent_lookup = {}
    children_lookup = defaultdict(lambda: [])

    all_nodes = graph.get_all_node_ids()
    if not all_nodes:
        return ordering, parent_lookup, children_lookup

    stack = deque()
    discovered = defaultdict(lambda: False)
    unvisited_nodes = set(all_nodes)

    if root_node is None:
        root_node = all_nodes[0]

    if adjacency_lists is None:
        adj = lambda v: graph.neighbors(v)
    else:
        adj = lambda v: adjacency_lists[v]

    # --Initialize the stack, simulating the DFS call on the root node
    stack.appendleft(root_node)
    parent_lookup[root_node] = root_node

    # We're using a non-recursive implementation of DFS, since Python isn't great for deep recursion
    while True:
        # Main DFS Loop
        while len(stack) > 0:
            u = stack.popleft()

            if not discovered[u]:
                discovered[u] = True
                if u in unvisited_nodes:
                    unvisited_nodes.remove(u)
                ordering.append(u)
                neighbors = adj(u)
                # When adding the new nodes to the stack, we want to add them in reverse order so that
                # the order the nodes are visited is the same as with a recursive DFS implementation
                for n in neighbors[::-1]:
                    if discovered[n]:
                        # If the node already exists in the discovered nodes list
                        # we don't want to re-add it to the stack
                        continue
                    stack.appendleft(n)
                    parent_lookup[n] = u
                    children_lookup[u].append(n)

        # While there are still nodes that need visiting, repopulate the stack
        if len(unvisited_nodes) > 0:
            u = unvisited_nodes.pop()
            stack.appendleft(u)
        else:
            break

    return ordering, parent_lookup, children_lookup
103278
def minimum_spanning_subtree(self):
    ''''''
    dist = self.matrix('dense', copy=True)
    dist[dist==0] = np.inf
    np.fill_diagonal(dist, 0)
    mst = ssc.minimum_spanning_tree(dist)
    return self.__class__.from_adj_matrix(mst + mst.T)
62497
def print_tree(graph, tails, node_id_map):
    """"""
    # Example:
    # |
    # | 5
    # *  a {0, 1, 2, 3, 4}
    # |
    # | 6
    # |\
    # * |  b {0, 1, 2, 3}
    # | *  n {4}
    # | |
    # | | 7
    # * |  c {0, 1, 2, 3}
    # | *  o {4}
    # | |
    # | | 8
    # |\ \
    # * | |  i {2, 3}
    # | * |  d {0, 1}
    # | | *  p {4}
    # | | |
    # | | | 9
    # * | |  j {2, 3}
    # | * |  e {0, 1}
    # | | *  q {4}
    # | | |
    # | | | 10
    # * | |  k {2, 3}
    # | * |  f {0, 1}
    # | | *  r {4}
    # | | |
    # | | | 11
    # |\ \ \
    # | | |\ \
    # * | | | |    g {0}
    # | * | | |    h {1}
    # |   * | |    l {2}
    # |   | * |    m {3}
    # |   |   *    s {4}
    # |  /   /
    # | |  /
    # | | | 12
    # * | |   t {0}
    # | * |   u {2}
    # | | *   v {4}
    # | |
    # | | 13
    # * |   w {0}
    # | *   x {2}
    # |
    # | 14
    # *   y {0}
    # | 15
    # *   z {0}

    walker = graph.walk()
    next_block_num, next_parent, next_siblings = next(walker)
    prev_cliques = []

    done = False
    while not done:
        cliques = {}
        block_num = next_block_num

        # Read all the cliques for this block number
        try:
            while block_num == next_block_num:
                cliques[next_parent] = next_siblings
                next_block_num, next_parent, next_siblings = next(walker)
        except StopIteration:
            # Do one last iteration after we've consumed the entire graph
            done = True

        print_cliques(prev_cliques, cliques, node_id_map)

        print_block_num_row(block_num, prev_cliques, cliques)

        print_splits(prev_cliques, cliques)

        print_folds(prev_cliques, cliques)

        prev_cliques = build_ordered_cliques(prev_cliques, cliques)

    print_cliques(prev_cliques, [], node_id_map)
1041832
private void createMDAGNode(SimpleMDAGNode current, int fromIndex, MDAGNode[] toNodeArray, MDAGNode[] fromNodeArray)
    {
        MDAGNode from = (fromIndex == -1 ? sourceNode : toNodeArray[fromIndex]);
        int transitionSetBegin = current.getTransitionSetBeginIndex();
        int onePastTransitionSetEnd = transitionSetBegin + current.getOutgoingTransitionSetSize();

        for (int i = transitionSetBegin; i < onePastTransitionSetEnd; i++)
        {
            SimpleMDAGNode targetNode = mdagDataArray[i];
            if (toNodeArray[i] != null)
            {
                fromNodeArray[fromIndex].addOutgoingTransition(current.getLetter(), fromNodeArray[i]);
                toNodeArray[fromIndex] = fromNodeArray[i];
                continue;
            }
            toNodeArray[i] = from.addOutgoingTransition(targetNode.getLetter(), targetNode.isAcceptNode());
            fromNodeArray[i] = from;
            createMDAGNode(targetNode, i, toNodeArray, fromNodeArray);
        }
    }