Compute the depth of the tree (depth of a leaf=0).
335045
def depth(self):
        
        return self.fold_up(lambda n, fl, fg: max(fl + 1, fg + 1), lambda leaf: 0)
759462
def length_at(self, depth):
        
        if depth == 0:
            return 1

        counter = 0
        for dict_tree in self.values_at(depth - 1):
            counter += len(dict_tree)
        return counter
354547
def qbe_tree(graph, nodes, root=None):
    
    if root:
        start = root
    else:
        index = random.randint(0, len(nodes) - 1)
        start = nodes[index]
    # A queue to BFS instead DFS
    to_visit = deque()
    cnodes = copy(nodes)
    visited = set()
    # Format is (parent, parent_edge, neighbor, neighbor_field)
    to_visit.append((None, None, start, None))
    tree = {}
    while len(to_visit) != 0 and nodes:
        parent, parent_edge, v, v_edge = to_visit.pop()
        # Prune
        if v in nodes:
            nodes.remove(v)
        node = graph[v]
        if v not in visited and len(node) > 1:
            visited.add(v)
            # Preorder process
            if all((parent, parent_edge, v, v_edge)):
                if parent not in tree:
                    tree[parent] = []
                if (parent_edge, v, v_edge) not in tree[parent]:
                    tree[parent].append((parent_edge, v, v_edge))
                if v not in tree:
                    tree[v] = []
                if (v_edge, parent, parent_edge) not in tree[v]:
                    tree[v].append((v_edge, parent, parent_edge))
            # Iteration
            for node_edge, neighbor, neighbor_edge in node:
                value = (v, node_edge, neighbor, neighbor_edge)
                to_visit.append(value)
    remove_leafs(tree, cnodes)
    return tree, (len(nodes) == 0)
757007
@Override
    public int getDepth() {
        if (depth == UNSET) {
            if (hasParent()) {
                depth = parent.getDepth() + 1;
            } else {
                depth = 0;
            }
        }
        return depth;
    }
203680
def rank(self, value):
        """"""
        i = 0
        n = len(self._tree)
        rank = 0
        count = 0
        while i < n:
            cur = self._tree[i]
            if value < cur:
                i = 2 * i + 1
                continue
            elif value > cur:
                rank += self._counts[i]
                # subtract off the right tree if exists
                nexti = 2 * i + 2
                if nexti < n:
                    rank -= self._counts[nexti]
                    i = nexti
                    continue
                else:
                    return (rank, count)
            else:  # value == cur
                count = self._counts[i]
                lefti = 2 * i + 1
                if lefti < n:
                    nleft = self._counts[lefti]
                    count -= nleft
                    rank += nleft
                    righti = lefti + 1
                    if righti < n:
                        count -= self._counts[righti]
                return (rank, count)
        return (rank, count)
569812
private int compareToLastRow(int depth)
        {
            for (int i = 0 ; i <= depth ; i++)
            {
                int p = currentRow[i], l = lastRow[i], r = clusteringComponents[i].size();
                if ((p == l) | (r == 1))
                    continue;
                return p - l;
            }
            return 0;
        }
435820
function tightTree(t, g) {
  function dfs(v) {
    _.forEach(g.nodeEdges(v), function(e) {
      var edgeV = e.v,
        w = (v === edgeV) ? e.w : edgeV;
      if (!t.hasNode(w) && !slack(g, e)) {
        t.setNode(w, {});
        t.setEdge(v, w, {});
        dfs(w);
      }
    });
  }

  _.forEach(t.nodes(), dfs);
  return t.nodeCount();
}
671906
def check
      branch_depth = nil

      traverse do |node, position, stack|
        if position == 0
          if node.parent
            # After a split the nodes will only have half the maximum keys.
            # For branch nodes one of the split nodes will have even 1 key
            # less as this will become the branch key in a parent node.
            if node.keys.size < min_keys - (node.is_leaf? ? 0 : 1)
              node.error "BigTree node #{node._id} has too few keys"
              return false
            end
          end

          if node.keys.size > @tree.node_size
            node.error "BigTree node must not have more then " +
              "#{@tree.node_size} keys, but has #{node.keys.size} keys"
            return false
          end

          last_key = nil
          node.keys.each do |key|
            if last_key && key < last_key
              node.error "Keys are not increasing monotoneously: " +
                "#{node.keys.inspect}"
              return false
            end
            last_key = key
          end

          if node.is_leaf?
            if branch_depth
              unless branch_depth == stack.size
                node.error "All leaf nodes must have same distance from root"
                return false
              end
            else
              branch_depth = stack.size
            end
            if node.prev_sibling.nil?
              if @tree.first_leaf != node
                node.error "Leaf node #{node._id} has no previous sibling " +
                  "but is not the first leaf of the tree"
                return false
              end
            elsif node.prev_sibling.next_sibling != node
              node.error "next_sibling of previous sibling does not point to " +
                "this node"
              return false
            end
            if node.next_sibling.nil?
              if @tree.last_leaf != node
                node.error "Leaf node #{node._id} has no next sibling " +
                  "but is not the last leaf of the tree"
                return false
              end
            elsif node.next_sibling.prev_sibling != node
              node.error "previous_sibling of next sibling does not point to " +
                "this node"
              return false
            end
            unless node.keys.size == node.values.size
              node.error "Key count (#{node.keys.size}) and value " +
                "count (#{node.values.size}) don't match"
                return false
            end
            if node.children
              node.error "children must be nil for a leaf node"
              return false
            end
          else
            if node.values
              node.error "values must be nil for a branch node"
              return false
            end
            unless node.children.size == node.keys.size + 1
              node.error "Key count (#{node.keys.size}) must be one " +
                "less than children count (#{node.children.size})"
                return false
            end
            node.children.each_with_index do |child, i|
              unless child.is_a?(BigTreeNode)
                node.error "Child #{i} is of class #{child.class} " +
                  "instead of BigTreeNode"
                return false
              end
              unless child.parent.is_a?(BigTreeNode)
                node.error "Parent reference of child #{i} is of class " +
                  "#{child.class} instead of BigTreeNode"
                return false
              end
              if child == node
                node.error "Child #{i} point to self"
                return false
              end
              if stack.include?(child)
                node.error "Child #{i} points to ancester node"
                return false
              end
              unless child.parent == node
                node.error "Child #{i} does not have parent pointing " +
                  "to this node"
                return false
              end
              if i > 0
                unless node.children[i - 1].next_sibling == child
                  node.error "next_sibling of node " +
                    "#{node.children[i - 1]._id} " +
                    "must point to node #{child._id}"
                  return false
                end
              end
              if i < node.children.length - 1
                unless child == node.children[i + 1].prev_sibling
                  node.error "prev_sibling of node " +
                    "#{node.children[i + 1]._id} " +
                    "must point to node #{child._id}"
                  return false
                end
              end
            end
          end
        elsif position <= node.keys.size
          # These checks are done after we have completed the respective child
          # node with index 'position - 1'.
          index = position - 1
          if node.is_leaf?
            if block_given?
              # If a block was given, call this block with the key and value.
              return false unless yield(node.keys[index], node.values[index])
            end
          else
            unless node.children[index].keys.last < node.keys[index]
              node.error "Child #{node.children[index]._id} " +
                "has too large key #{node.children[index].keys.last}. " +
                "Must be smaller than #{node.keys[index]}."
              return false
            end
            unless node.children[position].keys.first >= node.keys[index]
              node.error "Child #{node.children[position]._id} " +
                "has too small key #{node.children[position].keys.first}. " +
                "Must be larger than or equal to #{node.keys[index]}."
              return false
            end
          end
        end
      end

      true
    end
1015789
def _depth(self):
        """"""
        terminals = [0]
        depth = 1
        for node in self.program:
            if isinstance(node, _Function):
                terminals.append(node.arity)
                depth = max(len(terminals), depth)
            else:
                terminals[-1] -= 1
                while terminals[-1] == 0:
                    terminals.pop()
                    terminals[-1] -= 1
        return depth - 1
1344942
def __leaf(i, j, first, maxfirst, prevleaf, ancestor):
    
    jleaf = 0
    if i<=j or first[j] <= maxfirst[i]: return -1, jleaf
    maxfirst[i] = first[j]
    jprev = prevleaf[i]
    prevleaf[i] = j
    if jprev == -1: jleaf = 1
    else: jleaf = 2
    if jleaf == 1: return i, jleaf
    q = jprev
    while q != ancestor[q]: q = ancestor[q]
    s = jprev
    while s != q:
        sparent = ancestor[s]
        ancestor[s] = q
        s = sparent
    return q, jleaf
412907
def distanceTo(self, tree):
        '''
        
        '''
        return ViewClient.distance(ViewClient.__pickleable(self.views), tree)
793603
def depth_score(self, n, m):
        
        if n == 0:
            return 0.0

        # dopt is the optimal maximum depth of the tree
        dopt = 1 + int(floor(l2(m)))
        f = 1 / float(1 + n - dopt)
        return f * self.depth_score_helper(1, dopt)
582089
public void init()
    {
        // determine the depth to which we can safely split the tree
        byte sizedepth = (byte)(Math.log10(maxsize) / Math.log10(2));
        byte depth = (byte)Math.min(sizedepth, hashdepth);

        root = initHelper(fullRange.left, fullRange.right, (byte)0, depth);
        size = (long)Math.pow(2, depth);
    }
1137645
function() {
			if (!this.children.length)
				return null;
				
			var deepestChild = this;
			while (deepestChild.children.length) {
				deepestChild = deepestChild.children[deepestChild.children.length - 1];
			}
			
			return deepestChild;
		}
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
91510
private double computeDepth() throws WikiApiException {
        Category root = wiki.getMetaData().getMainCategory();
        if (root == null) {
            logger.error("There is no root node for this wiki. Check the parameter that provides the name of the root node.");
            return 0.0;
        }
        // test whether the root category is in this graph
        if (!graph.containsVertex(root.getPageId())) {
            logger.error("The root node is not part of this graph. Cannot compute depth of this graph. Setting depth to 0.0");
            return 0.0;
        }
        double maxPathLength = 0.0;
        double[] returnValues = computeShortestPathLenghts(root.getPageId(), 0.0, maxPathLength, new HashSet<Integer>());
        maxPathLength         = returnValues[1];
        return maxPathLength;
    }
957685
def k_depth(d, depth, _counter=1):
        
        if depth == 0:
            yield d[_meta]["_rootname"]
        else:
            if _counter == depth:
                for key in DictTree.k(d):
                    yield key
            else:
                _counter += 1
                for node in DictTree.v(d):
                    for key in DictTree.k_depth(node, depth, _counter):
                        yield key