Builds the tree from the leaves that have been added.

        This function populates the tree from the leaves down non-recursively
978531
def build(self):
        
        self.order = MerkleTree.get_order(len(self.leaves))
        n = 2 ** self.order
        self.nodes = [b''] * 2 * n

        # populate lowest nodes with leaf hashes
        for j in range(0, n):
            if (j < len(self.leaves)):
                self.nodes[j + n - 1] = self.leaves[j].get_hash()
            else:
                break

        # now populate the entire tree
        for i in range(1, self.order + 1):
            p = 2 ** (self.order - i)
            for j in range(0, p):
                k = p + j - 1
                h = hashlib.sha256()
                l = self.nodes[MerkleTree.get_left_child(k)]
                if (len(l) > 0):
                    h.update(l)
                r = self.nodes[MerkleTree.get_right_child(k)]
                if (len(r) > 0):
                    h.update(r)
                self.nodes[k] = h.digest()
1298529
def add_child(self, tree):
        '''
        '''
        tree.parent = self
        self.children.append(tree)
        return tree
909152
def _build_tree(self):
        
        #find unassigned i*
        istar = np.argmin(self._x)

        #compute distances
        self._d = self.c[istar] - self._v
        _pred = np.zeros(self.n, dtype=np.int) + istar

        #initialize sets
        #READY: set of nodes visited and in the path (whose price gets
        #updated in augment)
        #SCAN: set of nodes at the bottom of the tree, which we need to
        #look at
        #T0DO: unvisited nodes
        _ready = np.zeros(self.n, dtype=np.bool)
        _scan = np.zeros(self.n, dtype=np.bool)
        _todo = np.zeros(self.n, dtype=np.bool) + True

        while True:
            #populate scan with minimum reduced distances
            if True not in _scan:
                mu = np.min(self._d[_todo])
                _scan[self._d == mu] = True
                _todo[_scan] = False
                j = np.argmin(self._y * _scan)
                if self._y[j] == -1 and _scan[j]:
                    return _pred, _ready, istar, j, mu

            #pick jstar from scan (scan always has at least 1)
            _jstar = np.argmax(_scan)

            #pick i associated with jstar
            i = self._y[_jstar]

            _scan[_jstar] = False
            _ready[_jstar] = True

            #find shorter distances
            newdists = mu + self.cred[i, :]
            shorter = np.logical_and(newdists < self._d, _todo)

            #update distances
            self._d[shorter] = newdists[shorter]

            #update predecessors
            _pred[shorter] = i

            for j in np.nonzero(np.logical_and(self._d == mu, _todo))[0]:
                if self._y[j] == -1:
                    return _pred, _ready, istar, j, mu
                _scan[j] = True
                _todo[j] = False
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;
  }
520315
def leaf_to_root(self):
        """"""
        node = self
        subp = []
        while node:
            if node.type == TYPE_ALTERNATIVES:
                node.alternatives.append(subp)
                if len(node.alternatives) == len(node.children):
                    #last alternative
                    subp = [tuple(node.alternatives)]
                    node.alternatives = []
                    node = node.parent
                    continue
                else:
                    node = node.parent
                    subp = None
                    break

            if node.type == TYPE_GROUP:
                node.group.append(subp)
                #probably should check the number of leaves
                if len(node.group) == len(node.children):
                    subp = get_characteristic_subpattern(node.group)
                    node.group = []
                    node = node.parent
                    continue
                else:
                    node = node.parent
                    subp = None
                    break

            if node.type == token_labels.NAME and node.name:
                #in case of type=name, use the name instead
                subp.append(node.name)
            else:
                subp.append(node.type)

            node = node.parent
        return subp
1232463
private void buildRuntimeTree() {
    updateRuntime();
    Runtime rootInfo = findRuntime();
    root = new RuntimeNode();
    root.setFrameName("_top");
    root.setRuntimeID(rootInfo.getRuntimeID());

    List<Runtime> runtimeInfos = Lists.newArrayList(runtimesList.values());
    runtimeInfos.remove(rootInfo);

    for (Runtime runtimeInfo : runtimeInfos) {
      addNode(runtimeInfo, root);
    }
  }
1071708
public function buildTree()
    {
        $this->assertTreeHasRootNode();
        if (null !== $this->tree) {
            return $this->tree;
        }

        return $this->tree = $this->root->getNode(true);
    }
808828
def reset_tree(self):
        
        self.tree = {}
        self.tree['leaves'] = []
        self.tree['levels'] = []
        self.tree['is_ready'] = False
1002183
def fill_tree(comments):
    
    if not comments:
        return

    it = iter(comments)
    first = next(it)
    extra_path_items = imap(_mark_as_root_path, first.root_path)
    return chain(extra_path_items, [first], it)
839878
def uproot(tree):
        
        uprooted = tree.copy()
        uprooted.parent = None
        for child in tree.all_children():
            uprooted.add_general_child(child)
        return uprooted
839673
def build_tree(self):
        """"""
        for spec in self.specs:
            if spec.ismodule:
                self.modules.append(Module(spec.name, spec.path, dsm=self))
            else:
                self.packages.append(Package(
                    spec.name, spec.path,
                    dsm=self, limit_to=spec.limit_to,
                    build_tree=True,
                    build_dependencies=False,
                    enforce_init=self.enforce_init))
685294
def expandtree(self, model=None):
        
        if model and not self.columns:
            schema = model.schema()
            defaults = schema.columns(flags=orb.Column.Flags.AutoExpand).keys()
            defaults += schema.collectors(flags=orb.Collector.Flags.AutoExpand).keys()
        else:
            defaults = []

        expand = self.expand or defaults
        if not expand:
            return {}

        def build_tree(parts, tree):
            tree.setdefault(parts[0], {})
            if len(parts) > 1:
                build_tree(parts[1:], tree[parts[0]])

        tree = {}
        for branch in expand:
            build_tree(branch.split('.'), tree)

        return tree
184081
def _grow_trees(self):
        
        if self.grow_method == GROW_AUTO_INCREMENTAL:
            self.tree_kwargs['auto_grow'] = True
        
        while len(self.trees) < self.size:
            self.trees.append(Tree(data=self.data, **self.tree_kwargs))
1255539
def build_subtree_strut(self, result, *args, **kwargs):
        
        items = list(result)
        root_elem = {"node": None, "children": OrderedDict()}
        if len(items) == 0:
            return root_elem
        for _, node in enumerate(items):
            new_elem = {"node": node.Resource, "children": OrderedDict()}
            path = list(map(int, node.path.split("/")))
            parent_node = root_elem
            normalized_path = path[:-1]
            if normalized_path:
                for path_part in normalized_path:
                    parent_node = parent_node["children"][path_part]
            parent_node["children"][new_elem["node"].resource_id] = new_elem
        return root_elem
1056542
def get_tree(cls, parent=None):
        
        if parent:
            depth = parent.get_depth() + 1
            results = [parent]
        else:
            depth = 1
            results = []
        cls._get_tree_recursively(results, parent, depth)
        return results
639780
public function RebuildTree() {
      // Grab all of the categories.
      $Categories = $this->SQL->Get('Category', 'TreeLeft, Sort, Name');
      $Categories = Gdn_DataSet::Index($Categories->ResultArray(), 'CategoryID');

      // Make sure the tree has a root.
      if (!isset($Categories[-1])) {
         $RootCat = array('CategoryID' => -1, 'TreeLeft' => 1, 'TreeRight' => 4, 'Depth' => 0, 'InsertUserID' => 1, 'UpdateUserID' => 1, 'DateInserted' => Gdn_Format::ToDateTime(), 'DateUpdated' => Gdn_Format::ToDateTime(), 'Name' => 'Root', 'UrlCode' => '', 'Description' => 'Root of category tree. Users should never see this.', 'PermissionCategoryID' => -1, 'Sort' => 0, 'ParentCategoryID' => NULL);
         $Categories[-1] = $RootCat;
         $this->SQL->Insert('Category', $RootCat);
      }

      // Build a tree structure out of the categories.
      $Root = NULL;
      foreach ($Categories as &$Cat) {
         if (!isset($Cat['CategoryID']))
            continue;
         
         // Backup category settings for efficient database saving.
         try {
            $Cat['_TreeLeft'] = $Cat['TreeLeft'];
            $Cat['_TreeRight'] = $Cat['TreeRight'];
            $Cat['_Depth'] = $Cat['Depth'];
            $Cat['_PermissionCategoryID'] = $Cat['PermissionCategoryID'];
            $Cat['_ParentCategoryID'] = $Cat['ParentCategoryID'];
         } catch (Exception $Ex) {
         }

         if ($Cat['CategoryID'] == -1) {
            $Root =& $Cat;
            continue;
         }

         $ParentID = $Cat['ParentCategoryID'];
         if (!$ParentID) {
            $ParentID = -1;
            $Cat['ParentCategoryID'] = $ParentID;
         }
         if (!isset($Categories[$ParentID]['Children']))
            $Categories[$ParentID]['Children'] = array();
         $Categories[$ParentID]['Children'][] =& $Cat;
      }
      unset($Cat);

      // Set the tree attributes of the tree.
      $this->_SetTree($Root);
      unset($Root);

      // Save the tree structure.
      foreach ($Categories as $Cat) {
         if (!isset($Cat['CategoryID']))
            continue;
         if ($Cat['_TreeLeft'] != $Cat['TreeLeft'] || $Cat['_TreeRight'] != $Cat['TreeRight'] || $Cat['_Depth'] != $Cat['Depth'] || $Cat['PermissionCategoryID'] != $Cat['PermissionCategoryID'] || $Cat['_ParentCategoryID'] != $Cat['ParentCategoryID'] || $Cat['Sort'] != $Cat['TreeLeft']) {
            $this->SQL->Put('Category',
               array('TreeLeft' => $Cat['TreeLeft'], 'TreeRight' => $Cat['TreeRight'], 'Depth' => $Cat['Depth'], 'PermissionCategoryID' => $Cat['PermissionCategoryID'], 'ParentCategoryID' => $Cat['ParentCategoryID'], 'Sort' => $Cat['TreeLeft']),
               array('CategoryID' => $Cat['CategoryID']));
         }
      }
      $this->SetCache();
   }
1083025
def setup_tree(self):
        """"""
        self.tree.insert("", tk.END, text="Example 1", iid="1")
        self.tree.insert("", tk.END, text="Example 2", iid="2")
        self.tree.insert("2", tk.END, text="Example Child")
        self.tree.heading("#0", text="Example heading")